A dictionary stores values with labels instead of positions. Where a list says “the item at position 2”, a dictionary says “the item called email“.
person = {
"name": "Ada",
"age": 36,
"city": "Lahore",
}
print(person["name"]) # AdaWhy not just use a list?#
Compare these two ways of holding the same information:
person = ["Ada", 36, "Lahore"] # what is position 1 again?
person = {"name": "Ada", "age": 36, "city": "Lahore"} # obviousDictionaries are also fast to look up. Finding a key takes the same time whether the dictionary holds ten entries or a million.
Reading values safely#
person = {"name": "Ada", "age": 36}
print(person["name"]) # Ada
print(person["email"]) # KeyError: 'email'
print(person.get("email")) # None — no crash
print(person.get("email", "n/a")) # n/a — with a fallbackUse square brackets when the key must exist and a missing one is a real bug. Use get() when it is genuinely optional.
Adding, updating and removing#
person = {"name": "Ada"}
person["age"] = 36 # add
person["name"] = "Ada Lovelace" # update — same syntax
person.update({"city": "London", "age": 37})
del person["city"]
removed = person.pop("age") # remove and return
print(person)There is no separate “add” and “edit”. Assigning to a key creates it if it is missing and replaces it if it is not.
Checking what is there#
if "email" in person:
print(person["email"])
print(len(person)) # how many entries
print(list(person.keys())) # ['name']Looping#
prices = {"pen": 50, "book": 300, "bag": 1200}
for item in prices: # keys
print(item)
for price in prices.values():
print(price)
for item, price in prices.items(): # both — the one you want most often
print(f"{item}: Rs {price}")
print(sum(prices.values())) # 1550Nesting#
Dictionaries can hold lists, and lists can hold dictionaries. This is exactly the shape of data you get back from most web APIs.
students = [
{"name": "Ada", "marks": [90, 85]},
{"name": "Sam", "marks": [70, 78]},
]
for student in students:
average = sum(student["marks"]) / len(student["marks"])
print(f"{student['name']}: {average}")Note the single quotes inside the f-string braces — you cannot reuse double quotes there.
Counting with a dictionary#
A classic use: tallying how often things appear.
words = ["code", "test", "code", "ship", "code"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'code': 3, 'test': 1, 'ship': 1}Questions people ask#
Can a dictionary key be anything?
Keys must be unchangeable types — strings, numbers and tuples work; lists do not. Strings are by far the most common.
Are dictionaries ordered?
Since Python 3.7, they keep the order you inserted things in. Do not rely on it for anything important, but it makes printing predictable.
What happens if I use the same key twice?
The last one wins. Keys are unique — assigning again replaces the previous value.
How is this different from JSON?
JSON is a text format that looks almost identical. json.loads() turns JSON text into a Python dictionary, and json.dumps() goes the other way.