Dictionaries in Python Tutorial
Dictionaries are a builtin data structure in python that’s designed to hold key value pairs. Lists and tuples are sequence types, sets/frozensets are set types, and dictionaries are mapping types. If you read about mapping types in the python library, you’ll see that as of python3.0 dictionaries are currently the only mapping type available. This will most likely change overtime as the python programming language continues to grow and evolve.
Like sequence types, the items in a dictionary can too be indexed but how it’s done is different. It uses a concept known as key/value pairs. The keys which must be an immutable type unlocks the value which can be any mutable type in python. In sequence types like strings and lists, the values can be accessed by their index. You can use any type to represent the values of a dictionary. One way to think of dictionaries is as key/value pairs. This tutorial will explore how to create dictionaries in python along with their functions and other uses.
How to create a dictionary
You can use one of the several builtin constructors for dictionaries to create one:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Here’s an example of how to create a dictionary using each of the following constructors:
class dict(**kwarg)
The parameter **kwarg stands for unlimited keyword arguments. An example of how to use it is listed below:
>>> colors = dict(y = 'yellow', b = 'brown', g = 'green')
>>> colors
{'y': 'yellow', 'b': 'brown', 'g': 'green'}
class dict(mapping, **kwarg)
A mapping is a collection of key/value pairs that permits key access to values. In other words, it maps keys to values.
day = {'Mon': 1, 'Tues': 2, 'Wed': 3, 'Thurs': 4, 'Fri': 5, 'Sat': 6, 'Sun': 7}
You could also rewrite the above dictionary as follows:
days = {
'Mon': 1,
'Tues': 2,
'Wed': 3,
'Thurs': 4,
'Fri': 5,
'Sat': 6,
'Sun': 7
}
class dict(iterable, **kwarg)
An iterable is in essence any object that can be iterated over. Strings, lists, tuples, sets, dictionaries, and generators are all iterables.
>>> dict([('a', 'apple'), ('b', 'banana'), ('c', 'coconut')])
{'a': 'apple', 'b': 'banana', 'c': 'coconut'}
Common Operators in Python
Many of the operators that’s available in sequence types and sets are also available in dictionaries. For example, membership testing, the for loop, and the len() function are also available for dictionaries in python. The below code snippets show some of these in action:
>>> 'm'in day
False
>>> 'wed' in day
False
>>> 'wed'.capitalize() in day
True
>>> 'Sunday' not in day
True
>>> len(day)
7
How Indexing Works in Dictionaries
As mentioned previously, indexing in dictionaries is a different animal from indexing in lists and tuples. Like list/tuples you use subscript notation, but in dictionaries you have keys instead of default numbers. The following code snippets shows how indexing in dictionaries work:
>>> auto_complete = {'a': 'amazon', 'b': 'bank of america', 'c': 'calculator'}
>>> auto_complete['a']
'amazon'
>>> auto_complete['b']
'bank of america'
>>> auto_complete['c']
'calculator'
>>> auto_complete['c'] = 'costco'
>>> auto_complete
{'a': 'amazon', 'b': 'bank of america', 'c': 'costco'}
There’s built-in methods in the dictionary class that allows you to access the items, keys, and values of a dictionary.
A Sample of Some of the Methods Available for Dictionaries
Some of the methods available for dictionaries are items(), keys(), values(), fromkeys(), get(), pop(), popitem(), copy(), clear(), update(), and setdefault(). In the following code snippets I’ll show how to make use of some of these methods:
>>> weekday.items()
dict_items([('1', 'Mon'), ('2', 'Tues'), ('3', 'Wed'), ('4', 'Thurs'), ('5', 'Fri')])
>>> weekday.keys()
dict_keys(['1', '2', '3', '4', '5'])
>>> weekday.values()
dict_values(['Mon', 'Tues', 'Wed', 'Thurs', 'Fri'])
# gets value when key is passed
>>> weekday.get('3')
'Wed'
>>> weekday.fromkeys(range(10), 1)
{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}
>>> weekday.fromkeys(range(1, 6), 1)
{1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
# add new items to dictionary
>>> weekday.update({'6': 'Sat', '7': 'Sun'})
>>> weekday
{'1': 'Mon', '2': 'Tues', '3': 'Wed', '4': 'Thurs', '5': 'Fri', '6': 'Sat', '7': 'Sun'}
>>> week = weekday.copy()
>>> week
{'1': 'Mon', '2': 'Tues', '3': 'Wed', '4': 'Thurs', '5': 'Fri', '6': 'Sat', '7': 'Sun'}
# requires key
>>> weekday.pop('3')
# doesn’t require key
'Wed'>>> weekday.popitem()
('7', 'Sun')
# searches for a key in the dictionary
>>> weekday.setdefault('4')
'Thurs'
>>> weekday.clear()
>>> weekday
{}
Looping over dictionaries:
You can iterate over dictionaries using the for loop as indicated in the code snippet below:
>>> letters = {'a': 'apples', 'b': 'banana', 'c': 'coconut', 'd': 'durian'}
>>> for keys in letters:
print(keys)
a
b
c
d
This is good for just accessing the keys, but what if you also want to access the keys and values? We’ll have to use two variables to keep track of the key/value pairs and the items() function so that we can iterate over each key/value pair as shown in the updated code snippet:
>>> for keys, values in letters.items():
... print(keys, values)
a apples
b banana
c coconut
d durian
You could alternatively iterate over the dictionary using a single variable and the items() method to get the key/value mappings as a tuple indicated in the code snippet below:
>>> for items in letters.items():
... print(items)
('a', 'apples')
('b', 'banana')
('c', 'coconut')
('d', 'durian')
If you want to get just the corresponding count for each key then you can use the enumerate() function as shown in the code snippet below:
>>> for count, key in enumerate(letters):
... print(count, key)
0 a
1 b
2 c
3 d
If you want to access only the values of a dictionary then use a for loop in conjunction with the values() function as shown below:
>>> for x in letters.values():
... print(x)
apples banana coconut durian