Python dict()
Function
The dict()
function in Python is used to create a dictionary. A dictionary is an unordered collection of key-value pairs, where each key must be unique and immutable.
Syntax
dict(**kwargs)
dict(mapping)
dict(iterable)
Parameters:
**kwargs
– Key-value pairs as keyword arguments (e.g.,name="Alice"
)mapping
– Another dictionary or mapping objectiterable
– An iterable with key-value pairs, like a list of tuples
Returns:
- A new dictionary object.
Example 1: Creating an Empty Dictionary
d = dict()
print(d)
{}
Example 2: Using Keyword Arguments
person = dict(name="Alice", age=25)
print(person)
{'name': 'Alice', 'age': 25}
Example 3: From List of Tuples
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)
print(d)
{'a': 1, 'b': 2}
Example 4: From Another Dictionary
original = {'x': 10, 'y': 20}
copy = dict(original)
print(copy)
{'x': 10, 'y': 20}
Use Case: Why Use dict()
?
- To dynamically create a dictionary from data
- To convert other mappings or iterable pairs into a dictionary
- To copy an existing dictionary
Common Mistakes
- Keys must be unique: Later keys overwrite earlier ones
- Keys must be hashable: Lists or other dictionaries cannot be keys
- Syntax error: Trying to use non-string keys with keyword arguments (e.g.,
dict(1="a")
is invalid)
Interview Tip
The dict()
function is often used to build frequency maps or group data. Understanding how to use dict()
from tuples or with zip()
is useful in many coding interviews.
Summary
dict()
creates dictionaries from keyword arguments, mappings, or iterable pairs- Dictionaries store key-value pairs
- Keys must be unique and immutable
Practice Problem
Convert two lists into a dictionary using dict()
and zip()
:
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
result = dict(zip(keys, values))
print(result)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Try changing the values and see how the dictionary updates!