Python Basics — Creating Dictionaries
Creating Dictionaries
A dictionary maps keys to values. Think of it like a real dictionary: you look up a word (key) and get its definition (value).
Literal Syntax
# Curly braces with key: value pairs
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person)
# {'name': 'Alice', 'age': 30, 'city': 'New York'}
dict() Constructor
# From keyword arguments
person = dict(name="Alice", age=30, city="New York")
print(person)
# {'name': 'Alice', 'age': 30, 'city': 'New York'}
# From list of tuples
pairs = [("name", "Bob"), ("age", 25), ("city", "London")]
person = dict(pairs)
print(person)
# {'name': 'Bob', 'age': 25, 'city': 'London'}
# From zip
keys = ["name", "age", "city"]
values = ["Charlie", 35, "Paris"]
person = dict(zip(keys, values))
print(person)
# {'name': 'Charlie', 'age': 35, 'city': 'Paris'}
dict.fromkeys()
Create a dictionary with specified keys and a shared default value:
keys = ["a", "b", "c"]
d = dict.fromkeys(keys, 0)
print(d) # {'a': 0, 'b': 0, 'c': 0}
# Without default — values are None
d = dict.fromkeys(keys)
print(d) # {'a': None, 'b': None, 'c': None}
Warning: If the default is a mutable object, all keys share the same object:
d = dict.fromkeys(["a", "b", "c"], [])
d["a"].append(1)
print(d) # {'a': [1], 'b': [1], 'c': [1]} ← all changed!
Dictionary Ordering
Since Python 3.7, dictionaries preserve insertion order:
d = {"c": 3, "a": 1, "b": 2}
for key in d:
print(key, end=" ")
# c a b (insertion order preserved)
Valid Key Types
Keys must be hashable — immutable types that have a hash value:
# ✅ Valid keys
d = {
"name": "Alice", # string
42: "answer", # integer
3.14: "pi", # float
(1, 2): "coordinates", # tuple
True: "boolean", # bool
}
# ❌ Invalid keys (mutable types)
# d = {[1, 2]: "list"} # TypeError: unhashable type: 'list'
# d = { {}: "dict" } # TypeError: unhashable type: 'dict'
Empty Dictionaries
empty1 = {}
empty2 = dict()
print(len(empty1)) # 0
print(bool(empty1)) # False (empty = falsy)
print(type(empty1)) # <class 'dict'>
Note:
{}creates an empty dict, not an empty set. Useset()for empty sets.
Duplicate Keys
If you define duplicate keys, the last value wins:
d = {"a": 1, "b": 2, "a": 3}
print(d) # {'a': 3, 'b': 2}
Mixed Value Types
Values can be any type:
profile = {
"name": "Alice",
"age": 30,
"scores": [95, 87, 92],
"address": {
"city": "New York",
"zip": "10001"
},
"active": True
}
Summary
- Create with
{},dict(),dict.fromkeys(), ordict(zip(keys, values)) - Keys must be hashable (strings, numbers, tuples)
- Values can be any type
- Insertion order is preserved (Python 3.7+)
- Duplicate keys keep the last value
{}creates an empty dict, not a set
Next up: Accessing & Modifying Dictionaries →