Dictionaries and Sets
Store things by name, and keep a list of unique things
- create a dictionary and read a value by its key,
- add, change, and remove dictionary items safely,
- loop over keys, values, and pairs,
- build a set to remove duplicates and check membership fast.
1. What is a dictionary?
Think of a real paper dictionary: you look up a word and find its meaning. A Python dictionary works the same way — you look up a key and get its value.
A phone's contacts app is a perfect example: you type a name (the key) and it gives you a phone number (the value). You do not care that the name is the 5th contact — you find it by name.
We write a dictionary with curly braces { }, and each pair is key: value:
# A dictionary maps keys to values
ages = {"Sam": 12, "Mia": 11, "Leo": 13}
print(ages["Mia"])Output:
11
The keys here are the names "Sam", "Mia", "Leo". Writing ages["Mia"] asks the dictionary: "what value is stored under Mia?" The answer is 11.
2. Adding, changing, and removing
A dictionary can grow and change. Use dict[key] = value to add a new pair or to change an existing one, and del to remove a pair:
ages = {"Sam": 12, "Mia": 11}
ages["Leo"] = 13 # add a new key
ages["Sam"] = 15 # change an existing value
del ages["Mia"] # remove a key
print(ages)Output:
{'Sam': 15, 'Leo': 13}
Because "Sam" already existed, writing to it changed the value from 12 to 15. Because "Leo" was new, it was added. And del ages["Mia"] removed Mia completely.