Dictionary ¶
Lists allow us to store ordered collections of data which can be flexibly accessed via indices. However, frequently we need an alternative access pattern—looking up values by a descriptive key rather than numerical index. This is enabled in Python using dictionaries.
Dictionaries provide a flexible mapping of unique keys to associated values, like a real world dictionary maps words to definitions. Defining a dictionary uses braces with colons separating keys and values.
In [18]:
Copied!
person_favorites = {
"color": "blue",
"food": ["Chinese", "Thai", "American"],
"number": 32,
}
print(person_favorites)
person_favorites = {
"color": "blue",
"food": ["Chinese", "Thai", "American"],
"number": 32,
}
print(person_favorites)
{'color': 'blue', 'food': ['Chinese', 'Thai', 'American'], 'number': 32}
Dictionaries have some key capabilities:
- Store mappings of objects to easy retrieval by descriptive keys;
- High performance lookup time even for large data sets;
- Keys can use many immutable types: strings, numbers, tuples;
- Values can be any Python object;
- Extensible structure allowing easy growth.
In [19]:
Copied!
print(person_favorites.keys())
print(person_favorites.keys())
dict_keys(['color', 'food', 'number'])
In [20]:
Copied!
print(person_favorites["color"])
print(person_favorites["food"])
print(person_favorites["number"])
print(person_favorites["color"])
print(person_favorites["food"])
print(person_favorites["number"])
blue ['Chinese', 'Thai', 'American'] 32
In [21]:
Copied!
person_favorites["color"] = "red"
print(person_favorites)
person_favorites["color"] = "red"
print(person_favorites)
{'color': 'red', 'food': ['Chinese', 'Thai', 'American'], 'number': 32}
In [22]:
Copied!
person_favorites["city"] = "Pittsburgh"
print(person_favorites)
person_favorites["city"] = "Pittsburgh"
print(person_favorites)
{'color': 'red', 'food': ['Chinese', 'Thai', 'American'], 'number': 32, 'city': 'Pittsburgh'}
In [23]:
Copied!
person_favorites["food"][2] = "Italian"
print(person_favorites)
person_favorites["food"][2] = "Italian"
print(person_favorites)
{'color': 'red', 'food': ['Chinese', 'Thai', 'Italian'], 'number': 32, 'city': 'Pittsburgh'}