A dict
(short for dictionary) is a key-value pair structure in Python, used to store and retrieve data efficiently. It’s one of the most important data structures in Python.
Simple Example
data = dict(name="Alice", age=25, city="New York")
print(data)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
This is the easiest way to create a dictionary without using {}
.
Syntax
dict(key1=value1, key2=value2, ...)
dict([(key1, value1), (key2, value2)]) # Using a list of tuples
dict({key1: value1, key2: value2}) # Using an existing dictionary
- Keys must be unique and immutable (
str
,int
,tuple
). - Values can be any data type.
1. Creating a Dictionary from a List of Tuples
Sometimes, you have key-value pairs in a list. Convert them easily:
pairs = [("name", "Bob"), ("age", 30)]
data = dict(pairs)
print(data)
# Output: {'name': 'Bob', 'age': 30}
Useful when transforming structured data into a dictionary.
2. Using dict()
to Copy a Dictionary
Need to make a copy of a dictionary? Use dict()
:
original = {"a": 1, "b": 2}
copy_dict = dict(original)
print(copy_dict)
# Output: {'a': 1, 'b': 2}
This is safer than =
assignment, which just creates a reference.
3. Creating an Empty Dictionary
Want to start with an empty dictionary?
data = dict() # Same as data = {}
data["key"] = "value"
print(data)
# Output: {'key': 'value'}
This is useful when building a dictionary dynamically.
4. Using dict()
for Named Arguments in Functions
Python functions with **kwargs
return a dictionary, making dict()
useful for handling them.
def person_info(**kwargs):
return dict(kwargs)
info = person_info(name="Charlie", age=40)
print(info)
# Output: {'name': 'Charlie', 'age': 40}
This helps collect and manage dynamic arguments easily.
Key Notes
- ✔
dict()
provides multiple ways to create dictionaries – use the one that fits your data. - ✔ Keys must be unique and immutable – avoid using lists or dictionaries as keys.
- ✔ Useful for copying, transforming, and managing structured data.
- ✔ Works well with
**kwargs
in functions – makes argument handling easy.
By using dict()
, you can organize, modify, and retrieve data efficiently, making it one of Python’s most essential tools. 🚀