Dictionaries
Dictionaries are a built-in data type for storing objects. They associate one object, called a key, with another, called a value. This association is called mapping, resulting in a key-value pair. You add key-value pairs to a dictionary, allowing you to find a key and get its corresponding value. However, you cannot use a value to find its key.
Dictionaries, like lists, are mutable, meaning you can add new key-value pairs to them. They are useful for storing data in pairs, such as storing friends' phone numbers:
phones = {
"John": "+7123456789",
"William": "+37520123456"
}
print(phones)
When creating a dictionary, use curly braces, separate keys from values with colons, and separate key-value pairs with commas. Unlike tuples, a single key-value pair does not need a trailing comma.
Once you create a dictionary, add key-value pairs using dictionary_name[key] = value, and look up a value using dictionary_name[key].
phones = {
"John": "+7123456789",
"William": "+37520123456"
}
phones['Gregory'] = 1234567890
print(phones['John'])
A dictionary value can be any object. In the example, the first two values are strings, and the last value, 1234567890, is an integer.
Unlike values, dictionary keys must be immutable. A key can be a string or a tuple, but not a list or a dictionary. Use in to check if a key is in a dictionary, and not in to check if it is absent.
phones = {
"John": "+7123456789",
"William": "+37520123456"
}
print("William" in phones) # True
Remove a key-value pair from a dictionary using del.
phones = {
"John": "+7123456789",
"William": "+37520123456"
}
del phones["William"]
You can store containers within other containers, such as lists inside a dictionary.
music = {
"rap": ["Basta", "Kravec", "Evil Spirit"],
"rock": ["Nautilus Pompilius", "Kino", "Aria"],
"djs": ["Paul Oakenfold", "Tiesto"]
}
In this example, the dictionary music has three keys, each associated with a list. Access these lists using their keys.
music = {
"rap": ["Basta", "Kravec", "Evil Spirit"],
"rock": ["Nautilus Pompilius", "Kino", "Aria"],
"djs": ["Paul Oakenfold", "Tiesto"]
}
print(music['rap']) # ['Basta', 'Kravec', 'Evil Spirit']
print(music['rock'][-1]) # Aria