Dictionaries in Python Revealed (Part 1)

by:

Share:  

A quick tour on how dictionaries work in the awesome Python Language (Part 1)



Dictionaries are mapping types

In Python, dictionaries are regarded are the king of data types.

You would be hard pressed to find any real python project which does not use dictionaries.

In a nutshell, a dictionary maps a key to a value. The key has to be hashable though. The value, however, can be any python object data type.

The dict() constructor can be used to create a new dictionary.

empty_dict = {} # creates an empty dict
another_empty_dict = dict() # creates another empty dict
type(empty_dict) # returns <class 'dict'>
empty_dict == another_empty_dict # returns True

Initialising a dictionary with key/value pairs

If you ever fiddled with JavaScript before, dictionaries closely mimic how objects work in JavaScript.

items = {'apples': 5, 'oranges': 3, 'bananas': '6'} # this creates a new dict with 3 key/value pairs

Accessing individual values from a dictionary

Values can be accessed using the indexing/slicing notation. If you try to access an item which is not present in the dictionary, a KeyError will be raised.

grades = {'jon': 30, 'adam': 51, 'mark': '56'}
grades['mark'] # returns '56'
grades['zoe'] # returns KeyError: 'zoe'

We can also access the keys, values or items using the dict.keys() , dict.values() and dict.items() methods:

grades.keys() # returns ['adam', 'jon', 'mark'] list
grades.values() # returns [51, 30, '56'] list
grades.items() # returns [('adam', 51), ('jon', 30), ('mark', '56')], a list of tuples

Adding items to a dictionary

The indexing/slicing notation is very useful here:

scores = {}
scores['teamC'] = 15 # scores is now {'teamC': 15}

The dict.update() method also allows an item to be added/updated into the result set.

scores = {}
scores.update({ 'teamA': 20 })
scores.update({ 'teamB': 30 })
scores # returns {'teamA': 20, 'teamB': 30}

Note that adding an item with an existing key already present in the dictionary will overwrite the previous key and value as keys are unique.

Removing items from a dictionary

The dict.pop() method allows an item to be removed from the result set. The dict.pop() method needs at least 1 argument.

scores = { 'teamA': 20, 'teamB': 30}
scores.pop('teamA') # removes the key/value of 'teamA'
scores.pop('teamB') # removes the key/value of 'teamB'

Another way is use to the del python keyword.

del scores['teamA'] # removes the key/value of 'teamA'

To remove the first item from the dictionary, we can also use the dict.popitem() method:

numbers = { 'a': 1, 'b': 2, 'c': 3}
numbers.popitem() # { 'a': 1 }

Membership testing in dictionaries

The in operator is used to demonstrate membership testing in Python and it's quite central when using dictionaries to check for keys/values being present. Using the in operator will always return a boolean result.

Here's an example:

numbers = { 'a': 1, 'b': 2, 'c': 3}
'a' in numbers # returns True
'd' in numbers # returns False

We can also be more explicit and check membership in the dict.keys() method:

numbers = { 'a': 1, 'b': 2, 'c': 3}
'a' in numbers.keys() # returns True
'e' in numbers.keys() # returns False

Likewise, to check for values rather than keys, we can simply use the dict.values() method:

numbers = { 'a': 1, 'b': 2, 'c': 3}
1 in numbers.values() # returns True
100 in numbers.values() # returns False

Counting items in a dictionary

We can use Python's built-in len() method to count the total number of key-value pairs in a dictionary.

scores = { 'teamA': 20, 'teamB': 30}
len(scores) # returns 2

Clearing all items from a dictionary

This demonstrates how we can remove all items from a specific list using the dict.clear()method.

scores = { 'teamA': 20, 'teamB': 30}
scores.clear() # scores is now {}, clean as a whistle.

Finding a specific key in a dictionary

We can use the dict.has_key() method to determine if a key is present in a dictionary. This method will return a boolean value of either True or False.

numbers = { 'a': 1, 'b': 2, 'c': 3}
numbers.has_key('a') # returns True
numbers.has_key('e') # returns False

Finding the value of a specific key in a dictionary

One way of finding the value given we know the key is using the dict.get() method. If the key is not present in the dictionary, a None value will be returned.

numbers = { 'a': 1, 'b': 2, 'c': 3}
numbers.get('a') # returns 1
numbers.get('e') # Errr..Zilch! returns None

To provide a default value other None, in case the key is not present, we can set an arbitrary value.

numbers = { 'a': 1, 'b': 2, 'c': 3}
numbers.get('f', 42) # returns 42 instead of None

A better way, however and one of my favourites is to use the dict.setdefault() method.

grades = {}
grades.setdefault('John', 54) # as the 'John' key is not present, the key is created, the value 54 assigned to it and the value of 54 is returned.
grades.setdefault('John', 45) # No effect as key exists now.

Do you use dictionaries in Python or want to suggest an improvement to this article? Please share it with us by leaving a reply below.

Stay tuned for Part 2.


About the Author

Alvin Luchmun
Alvin Luchmun is a freelance developer, trainer and co-founder at and currently lives in London. Alvin is passionate about anything tech/biz related but is also a firm believer in agile clean code, he loves preaching about code to fellow humanoids!.

Leave a comment