Dictionary Basics
January 10, 2018
Dictionary Basics
Dictionaries in Python allow us to work with data that has a key: value relationship, with the key in each dictionary being unique and immutable (cannot be modified).
Creating a Dictionary
An empty dictionary can be created by a pair of empty curly braces.
empty_dict = {}
print(empty_dict)
{}
The dict()
function produces the same result.
empty_dict = dict()
print(empty_dict)
{}
Expectedly, an empty dictionary is not very interesting. Let’s create a dictionary to store the ice cream preferences of Mary, Jane and June.
The items in a dictionary are enclosed in curly braces, with each key: value pair seperated by a colon.
preferences = {'Mary': 'vanilla',
'Jane': 'chocolate',
'June': 'chocolate'}
print(preferences)
{'Mary': 'vanilla', 'Jane': 'chocolate', 'June': 'chocolate'}
Accessing Data in a Dictionary
To retrive the girls’ names, we can use the keys()
function.
print(preferences.keys())
dict_keys(['Mary', 'Jane', 'June'])
values()
allows us to retrieve the flavors.
print(preferences.values())
dict_values(['vanilla', 'chocolate', 'chocolate'])
If we want to iterate on each key-value pair, we can use the items()
function.
for key, value in preferences.items():
print('Key: ' + key)
print('Value: ' + value + '\n')
Key: Mary
Value: vanilla
Key: Jane
Value: chocolate
Key: June
Value: chocolate
You can access values directly if you know the key.
print(preferences['Mary'])
vanilla
Removing Data from a Dictionary
There are two ways that we can remove data from a dictionary. The first is by using the del
keyword.
preferences['John'] = 'strawberry'
print(preferences['John'])
strawberry
del preferences['John']
print(preferences)
{'Mary': 'vanilla', 'Jane': 'chocolate', 'June': 'chocolate'}
The second way is by using the pop()
function. The key difference is that pop()
returns the value of the key that was removed.
preferences['John'] = 'strawberry'
print(preferences['John'])
strawberry
print('Result of pop function: ' + preferences.pop('John'))
print(preferences)
Result of pop function: strawberry
{'Mary': 'vanilla', 'Jane': 'chocolate', 'June': 'chocolate'}
Handling Missing Keys
When we attempt to access a non-existent key in the dictionary, it will result in a KeyError
. This is certainly not a desired behavior in any production system.
Let’s assume that we are given a list of words and tasked to count the number of times each word appears in the list. How can we do this using a dictionary, and without running into a KeyError
?
Below, you will see two ways that we can achieve this.
words = ['apple', 'apple', 'apple', 'banana', 'banana', 'cucumber']
word_counts = {}
for word in words:
word_counts.setdefault(word, 0)
word_counts[word] += 1
print(word_counts)
{'apple': 3, 'banana': 2, 'cucumber': 1}
An alternative method will be to create a defaultdict
(from Python’s in-built collection of high performance data structures)
from collections import defaultdict
words = ['apple', 'apple', 'apple', 'banana', 'banana', 'cucumber']
word_counts = defaultdict(int)
for word in words:
word_counts[word] += 1
print(word_counts)
defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'cucumber': 1})