A dictionary is a collection of key : value pairs. It lets you map one piece of information (the key) to another (the value), like a real dictionary: a word → its meaning.
student = {
"name": "Maria",
"age": 21,
"grade": "A"
}
empty_dict = {}
dict() Constructorcar = dict(brand="Tesla", model="Model 3", year=2023)
print(car)
Output:
{'brand': 'Tesla', 'model': 'Model 3', 'year': 2023}
Keys can be strings, numbers, or tuples (immutable types). Values can be any type.
data = {
1: "one",
2.5: "two point five",
(3, 4): "tuple key"
}
Try it out:
Access values using their keys.
person = {
"name": "Alex",
"age": 25,
"country": "Lithuania"
}
print(person["name"]) # Alex
print(person["age"]) # 25
Accessing a missing key causes a KeyError:
print(person["height"]) # ❌ KeyError
get()print(person.get("height")) # None
print(person.get("height", 0)) # 0 (default value)
Try it out:(you have to define "person")
person["height"] = 180 # adds new key
print(person)
person["age"] = 26 # updates value (define person first to test)
print(person)
person = {"name": "Alex", "age": 25, "country": "Lithuania"}
pop() – Remove by Keyage = person.pop("age")
print(age) # 25
print(person) # {"name": "Alex", "country": "Lithuania"}
del Statementdel person["country"]
print(person)
clear() – Remove All Itemsperson.clear()
print(person) # {}
person = {"name": "Alex", "age": 25, "country": "Lithuania"}
for key in person:
print(key)
for value in person.values():
print(value)
for key, value in person.items():
print(key, "->", value)
person = {"name": "Alex", "age": 25}
if "name" in person:
print("Name exists")
print(len(person)) # number of key-value pairs
person = {"name": "Alex", "age": 25, "country": "Lithuania"}
keys() – All Keysprint(person.keys()) # dict_keys(['name', 'age', 'country'])
values() – All Valuesprint(person.values()) # dict_values(['Alex', 25, 'Lithuania'])
items() – Key-Value Pairsprint(person.items()) # dict_items([('name', 'Alex'), ('age', 25), ...])
update() – Merge / Updateperson.update({"age": 30, "city": "Vilnius"})
print(person)
You can store dictionaries inside dictionaries to represent structured data.
users = {
"user1": {
"name": "Alex",
"age": 25
},
"user2": {
"name": "Maria",
"age": 22
}
}
print(users["user1"]["name"]) # Alex
for username, data in users.items():
print(username)
for key, value in data.items():
print(" ", key, ":", value)
Dictionaries can hold lists as values.
classroom = {
"students": ["Alex", "Maria", "John"],
"grades": [90, 85, 88]
}
print(classroom["students"][0]) # Alex
print(classroom["grades"][1]) # 85
Be careful: assigning with = copies the reference, not the data.
a = {"x": 1, "y": 2}
b = a # both refer to the same dictionary
b["x"] = 99
print(a) # {"x": 99, "y": 2}
Use copy() or dict() to make a shallow copy:
a = {"x": 1, "y": 2}
b = a.copy()
# or b = dict(a)
b["x"] = 99
print(a) # {"x": 1, "y": 2}
print(b) # {"x": 99, "y": 2}
Create dictionaries from loops in a compact way.
squares = {x: x * x for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
even_squares = {x: x * x for x in range(10) if x % 2 == 0}
print(even_squares)
A common use is counting word frequency.
sentence = "python is easy and python is powerful".split()
count = {}
for word in sentence:
count[word] = count.get(word, 0) + 1
print(count)
Output:
{'python': 2, 'is': 2, 'easy': 1, 'and': 1, 'powerful': 1}
|a = {"x": 1}
b = {"y": 2}
combined = a | b
print(combined) # {"x": 1, "y": 2}
a = {"x": 1}
b = {"y": 2}
combined = {**a, **b}
print(combined)
users = {}
while True:
username = input("Enter username (or 'exit'): ")
if username == "exit":
break
age = int(input("Enter age: "))
country = input("Enter country: ")
users[username] = {
"age": age,
"country": country
}
print(users)
| Mistake | Wrong | Correct |
|---|---|---|
| Accessing missing key directly | |
|
| Copying dictionary incorrectly | |
|
| Looping wrong over items | |
|
Use dictionaries when you need:
In this guide, you learned how to:
keys(), values(), and items()Dictionaries are one of the most powerful tools in Python and appear everywhere in real projects.