Python Dictionaries
A dictionary stores data as pairs of keys and values, like a word and its meaning.
Creating a Dictionary
Write key: value pairs inside curly brackets:
Example
student = {
"name": "Ali",
"age": 19,
"course": "Python"
}
print(student)
print(student["name"])
print(len(student)){'name': 'Ali', 'age': 19, 'course': 'Python'}
Ali
3Dictionaries keep the order you add items in, they are changeable, and keys must be unique.
Reading Values
Use the key in square brackets, or the get() method:
Example
student = {"name": "Ali", "age": 19}
print(student["age"])
print(student.get("city"))
print(student.get("city", "Karachi"))19 None Karachi
student["city"] would stop the program with a KeyError because the key does not exist. get() is safer: it returns None, or a default value you choose.
Adding and Changing Items
Give a value to a key. If the key exists, the value is replaced. If not, a new pair is added.
Example
prices = {"tea": 60, "samosa": 40}
prices["tea"] = 70 # change
prices["paratha"] = 80 # add
print(prices){'tea': 70, 'samosa': 40, 'paratha': 80}Removing Items
Example
prices = {"tea": 70, "samosa": 40, "paratha": 80}
prices.pop("samosa")
print(prices)
del prices["tea"]
print(prices){'tea': 70, 'paratha': 80}
{'paratha': 80}Looping Through a Dictionary
Example
marks = {"Maths": 88, "English": 76, "Urdu": 91}
for subject in marks:
print(subject)
for subject, score in marks.items():
print(f"{subject}: {score}")Maths English Urdu Maths: 88 English: 76 Urdu: 91
Useful Methods
| Method | What it returns or does |
|---|---|
keys() | All keys |
values() | All values |
items() | All (key, value) pairs |
get(key, default) | The value, or the default if missing |
update(other) | Adds or replaces pairs from another dictionary |
pop(key) | Removes the key and returns its value |
Example
marks = {"Maths": 88, "English": 76, "Urdu": 91}
print(list(marks.keys()))
print(sum(marks.values()))
print("Urdu" in marks)['Maths', 'English', 'Urdu'] 255 True
in checks the keys, not the values.
Nested Dictionaries
A value can itself be a dictionary or a list:
Example
students = {
"s1": {"name": "Ayesha", "marks": [80, 92]},
"s2": {"name": "Hamza", "marks": [70, 65]}
}
print(students["s1"]["name"])
print(students["s2"]["marks"][0])Ayesha 70
Exercise
Exercise
What does d.get("x", 0) return when the key "x" is not in the dictionary d?
