Learn to Use Python Dictionary
Dictionary data structure in Python is a way to store data; moreover, it is powerful and easy to use. Dictionaries are found in other languages as “associative memories” or “associative arrays”. In Python, a dictionary is an unordered set of key: value
pairs, with the requirement that each key is unique.
How should we use a dictionary in everyday development?
Let’s examine some common use cases with accompanying code examples. Let’s say you use many if/else
clauses in your code:
if name == "John":
print "This is John, he is an artist"
elif name == "Ted":
print "This is Ted, he is an engineer"
elif name == "Kennedy":
print "This is Kennedy, he is a teacher"
By using a dictionary, we can write the same code like this:
name_job_dict = {
"Josh": "This is John, he is an artist",
"Ted": "This is Ted, he is an engineer",
"Kenedy": "This is Kennedy, he is a teacher",
}
print name_job_dict[name]
The second use case is when we need a default value for a key:
def count_duplicates(numbers):
result = {}
for number in numbers:
if number not in result: # No need for if here
result[key] = 0
result[number] += 1
return result
By using setdefault
, we get cleaner code:
>>> def count_duplicates(numbers):
result = {}
for number in numbers:
result.setdefault(number, 0) # this is clearer
result[number] += 1
return result
We can also use the dictionary to manipulate lists:
>>> characters = {'a': 1, 'b': 2}
>>> characters.items() // return a copy of a dictionary’s list of (key, value) pairs (https://docs.python.org/2/library/stdtypes.html#dict.items)
[('a', 1), ('b', 2)]
>>> characters = [['a', 1], ['b', 2], ['c', 3]]
>>> dict(characters) // return a new dictionary initialized from a list (https://docs.python.org/2/library/stdtypes.html#dict)
{'a': 1, 'b': 2, 'c': 3}
If necessary, it is easy to change a dictionary form by switching the keys and values – changing {key: value}
to a new dictionary {value: key}
– also known as inverting the dictionary:
>>> characters = {'a': 1, 'b': 2, 'c': 3}
>>> invert_characters = {v: k for k, v in characters.iteritems()}
>>> invert_characters
{1: 'a', 2: 'b', 3: 'c'}
The final tip is related to exceptions. Developers should watch out for exceptions. One of the most annoying is the KeyError
exception. To handle this, developers must first check whether or not a key exists in the dictionary.
>>> character_occurrences = {'a': [], ‘b’: []}
>>> character_occurrences[‘c’]
KeyError: 'c'
>>> if ‘c’ not in character_occurrences:
character_occurrences[‘c’] = []
>>> character_occurrences[‘c’]
[]
>>> try:
print character_occurrences[‘d’]
except:
print “There is no character `d` in the string”
However, to achieve clean and easily testable code, avoiding exceptions catch and conditions is a must. So, this is cleaner and easier to understand if the defaultdict
, in collections, is used.
>>> from collections import defaultdict
>>> character_occurrences = defaultdict(list)
>>> character_occurrences['a']
[]
>>> character_occurrences[‘b’].append(10)
>>> character_occurrences[‘b’].append(11)
>>> character_occurrences[‘b’]
[10, 11]