Python Dictionaries
A dictionary stores pairs of a key and a value: a word and its meaning, a name and a phone number, a product and its price. You look a value up by its key, not by a position. Dictionaries are written with curly brackets, with a colon between each key and its value. Together with lists, they are the most important collection in Python.
Creating and reading
student = {"name": "Asha", "age": 21, "city": "Pune"}
print(student["name"])
print(student.get("age"))
print(student.get("email"))
print(student.get("email", "not given"))
print(len(student), "city" in student)Asha 21 None not given 3 True
Square brackets give the value for a key and raise a KeyError when the key does not exist. get returns None, or the default you give it, instead. in checks whether a key is in the dictionary.
Adding, changing and deleting
prices = {"tea": 20, "coffee": 35}
prices["juice"] = 50 # a new key: added
prices["tea"] = 25 # an existing key: changed
del prices["coffee"]
removed = prices.pop("juice")
print(prices, removed)
prices.update({"cake": 60, "tea": 22})
print(prices){'tea': 25} 50
{'tea': 22, 'cake': 60}Keys are unique: assigning to an existing key replaces its value. Dictionaries remember the order in which keys were first added.
Looping over a dictionary
stock = {"apples": 12, "bananas": 0, "mangoes": 7}
for item in stock:
print(item)
for item, count in stock.items():
status = "in stock" if count else "sold out"
print(f"{item:8} {count:3} {status}")
print(list(stock.keys()), sum(stock.values()))apples bananas mangoes apples 12 in stock bananas 0 sold out mangoes 7 in stock ['apples', 'bananas', 'mangoes'] 19
A plain loop gives the keys. items() gives key and value pairs, keys() the keys and values() the values.
Counting with a dictionary
A very common job is counting how often each thing appears. get with a default of 0 makes it a one-line loop body:
text = "to be or not to be"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts){'to': 2, 'be': 2, 'or': 1, 'not': 1}Values can be anything, even lists or other dictionaries, so dictionaries can describe complex data such as the contents of a JSON file. Keys must be immutable: strings, numbers or tuples.
Practice exercises
- Make a dictionary of three countries and their capitals, and print the capital of one of them.
- Add a fourth country, change one capital, and print all pairs with a loop.
- Count the letters of the word
"banana"in a dictionary. - Ask for a fruit name and print its price from a dictionary, or "not sold here" when it is missing.