Dictionaries or 'dicts' provide an unordered, mutable, sequence of key-value pairs or a mapping between keys and values. For more information check the official docs and w3schools. Keys have to be unique, values do not. Any immutable value (int, float, string, tuple) can be a key, thus lists and other dicts can't be keys. Values can be any type.
- Defining Dictionaries
- Accessing a Value with a Key:
dict[key]
- Accessing a Value with a Key Safely:
dict.get(key)
- Updating a Key-Value Pair:
dict[key] = value
- Adding a Key-Value Pair:
dict[key] = value
- Removing a Key-Value Pair:
del dict[key]
- Checking if a Key Exists:
key in dict
- Combining Dictionaries:
dict1.update(dict2)
- Retrieving Keys and Values
- Order
- Conversions
Dictionary literals are written using curly braces, and key-value pairs defined with colons and separated by commas.
{'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
The values of a dictionary are accessed by using the square-brackets with the key, similarly to how we access a specific element from a list using its index. If you use a key which does not exist in the dictionary, you'll get a KeyError.
fruits = {'apple': 1.0, 'banana': 1.5, 'pear': 0.75}
print(fruits['apple']) # 1.0
print(fruits['pear']) # 0.75
print(fruits['grapes']) # Throws KeyError
The get
method allows us to safely access a value with a key. If the key is not in the dictionary, it will return None
. You can also specify a second parameter as a default, which will be returned if the result is not found.
fruits = {'apple': 1.0, 'banana': 1.5, 'pear': 0.75}
print(fruits.get('apple')) # 1.0
print(fruits.get('grapes')) # None
print(fruits.get('grapes', 4.0)) # 4.0
Values can then be added or updated by using the assignment operator =
.
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
fruits['apple'] = 2.0
fruits['pear'] += 0.5
print(fruits) # {'apple': 2.0, 'pear': 2.0, 'grapes': 0.75}
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
fruits['banana'] = 0.25
print(fruits) # {'apple': 1.0, 'pear': 1.5, 'banana': 0.25, 'grapes': 0.75}
You can delete a key-value pair using the del
operator.
fruits = {'apple': 1.0, 'banana': 1.5, 'pear': 0.75}
del fruits['apple']
print(fruits) # {'banana': 1.5, 'pear': 0.75}
To check if a dictionary contains a key, use in
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
if 'apple' in fruits:
print('apple ' + str(fruits['apple'])) # 'apple 1.0'
To combine two dictionaries, use the .update()
type method. Note that it changes the given dict and does not return a new one.
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
fruits.update({'banana': 0.25})
fruits #> {'apple': 1.0, 'pear': 1.5, 'banana': 0.25, 'grapes': 0.75}
The dictionary merge operator | creates a new dictionary that is the result of merging two existing dictionaries. If keys in the first dictionary are also present in the second dictionary, the values from the second dictionary will be used in the resulting merged dictionary.
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
combined_fruits = fruits | {'banana': 0.25})
combined_fruits #> {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75, 'banana': 0.25 }
The dictionary update operator |= updates an existing dictionary in place by merging it with another dictionary. If keys in the first dictionary are also present in the second dictionary, their values will be updated with the values from the second dictionary.
fruits = {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
fruits |= {'grapes': 1, 'banana': 0.25})
fruits #> {'apple': 1.0, 'pear': 1.5, 'grapes': 1, 'banana': 0.25 }
There are a few type methods that allow you to view different parts of the dictionary. All produce sequences and not proper lists, so cast them to a list to use them normally.
list(fruits.keys()) #> ['pear', 'apple', 'grapes']
list(fruits.values()) #> [0.75, 1.0, 1.5]
list(fruits.items()) #> [('grapes', 0.75), ('apple', 1.0), ('pear', 1.5)]
Dictionary order is guaranteed to be insertion order. Note that updating a key does not affect the order.
fruits = {'apple': 1.0}
fruits['pear'] = 1.5
fruits['grapes'] = .75
print(grapes) # {'apple': 1.0, 'pear': 1.5, 'grapes': 0.75}
In python versions older than 3.7 dictionaries are unordered.
You can cast a sequences of two-tuples to a dictionary using dict()
. This means .items()
and dict()
are inverses.
names_and_fav_colors = [('Alice', 'red'), ('David', 'green')]
print(dict(names_and_fav_colors)) #> {'Alice': 'red', 'David': 'green'}
dict(names_and_fav_colors.items()) == names_and_fav_colors #> True
Dict comprehensions also look similar to list comprehensions, but with curly braces and colons.
names_to_ages = {'Amanda': 90, 'David': 50}
names_to_ages = {name: age / 2 for name, age in names_to_ages.items()}
print(names_to_ages) # {'Amanda': 45, 'David': 25}