Python Tutorial menu

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

python
student = {
    "name": "Ali",
    "age": 19,
    "course": "Python"
}
print(student)
print(student["name"])
print(len(student))
Output
{'name': 'Ali', 'age': 19, 'course': 'Python'}
Ali
3

Dictionaries 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

python
student = {"name": "Ali", "age": 19}
print(student["age"])
print(student.get("city"))
print(student.get("city", "Karachi"))
Output
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

python
prices = {"tea": 60, "samosa": 40}
prices["tea"] = 70        # change
prices["paratha"] = 80    # add
print(prices)
Output
{'tea': 70, 'samosa': 40, 'paratha': 80}

Removing Items

Example

python
prices = {"tea": 70, "samosa": 40, "paratha": 80}
prices.pop("samosa")
print(prices)
del prices["tea"]
print(prices)
Output
{'tea': 70, 'paratha': 80}
{'paratha': 80}

Looping Through a Dictionary

Example

python
marks = {"Maths": 88, "English": 76, "Urdu": 91}

for subject in marks:
    print(subject)

for subject, score in marks.items():
    print(f"{subject}: {score}")
Output
Maths
English
Urdu
Maths: 88
English: 76
Urdu: 91

Useful Methods

MethodWhat 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

python
marks = {"Maths": 88, "English": 76, "Urdu": 91}
print(list(marks.keys()))
print(sum(marks.values()))
print("Urdu" in marks)
Output
['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

python
students = {
    "s1": {"name": "Ayesha", "marks": [80, 92]},
    "s2": {"name": "Hamza", "marks": [70, 65]}
}
print(students["s1"]["name"])
print(students["s2"]["marks"][0])
Output
Ayesha
70

Exercise

Exercise

What does d.get("x", 0) return when the key "x" is not in the dictionary d?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp