Ridiculously Simple Tips for a Python Dictionary

onestop_databy:

Python

This tutorial teaches how to use the Python dictionary, and it will focus on dictionary get, append, update, sort, comprehension, etc. Moreover, it will convince you why you should use Python’s defaultdict rather than the type dict.

Dictionaries in Python is the representation of a data structure named hash tables, and this structure has a key and value where the key is used to quickly access the value.

1. Create a dictionary

A dictionary in Python can be initiated as follows:

>>> my_dict = {}

2. Add to Dictionary

Here we are adding keys as city name and values as country name:

>>> my_dict['San Diego'] = 'USA'
>>> my_dict['San Francisco'] = 'USA'
>>> my_dict['Shanghai'] = 'China'
>>> my_dict['Tokyo'] = 'Japan'

But it could have also be added all keys and values at once.

>>> my_dict = {'San Diego': 'USA', 'San Francisco': 'USA', 'San Francisco': 'USA', 'Shanghai': 'China',
           'Tokyo': 'Japan'

3. Values Dictionary

If you want to access the values for existing keys, this is how you would do: Pass the key and get the value.

# check value for key 'San Diego'
>>> my_dict['San Diego']
>>> 'USA'

# check value for Tokyo
>>> my_dict['Tokyo']
>>> 'Japan'

However, if you try to access the value for an unexisting key, you will get a KeyError message.

# try to access value for "Rio de janeiro"
>>> my_dict['Rio de Janeiro']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Rio de Janeiro'

Honestly, I don’t like getting error messages raised in Python, and I’m sure you too.

Luckily, this can be simply “fixed” by using defaultdict.

# import defaultdict
>>> from collections import defaultdict
# create hash table using defaultdict
>>> my_dict = defaultdict(str)

# add values to hash
>>> my_dict['San Diego'] = 'USA'
>>> my_dict['San Francisco'] = 'USA'
>>> my_dict['Shanghai'] = 'China'
>>> my_dict['Tokyo'] = 'Japan'

# check value for key 'San Diego'
>>> my_dict['San Diego']
>>> 'USA'

# check value for Tokyo
>>> my_dict['Tokyo']
>>> 'Japan'

# check key 'Rio de Janeiro'
>>> my_dict['Rio de Janeiro']
>>> ''

As you can see above, defaultdict does not raise an error message for non-existing keys!

4. Defaultdict: Getting this most out of a dict

Here is the thing, In the first example above, we could have avoided raising the error message by checking if the key was present in the hash table.

>>> targeted_key = 'Rio de Janeiro'
>>> my_dict[targeted_key] if targeted_key in my_dict else ''
>>> ''

However, I think it is just easier to use defaultdict and not have to check for the presence of the key.

Furthermore, I think defaultdict‘s real value is in cases where the value of the hash table is a list. For example, this means that we can just blindly add the element into the value-list rather than having to check if the key exists in the hash, creating an empty list to the hash, and then adding the element to the list. See below:

Using dict

# create hash
my_dict = {}

for value in range(5):
    if value % 2:
        key = "odd"
    else:
        key = "even"

    # check if key exists in dict, if not create it with an empty list
    if key not in my_dict:
        my_dict[key] = []

    # add value into list associated with the key
    my_dict[key].append(value)
>>> my_dict
>>> {'even': [0, 2, 4], 'odd': [1, 3]}

Using defaultdict

#import defaultdict
from collections import defaultdict

# create hash
my_dict = defaultdict(list)

for value in range(5):
    if value % 2:
        key = "odd"
    else:
        key = "even"

    # add value into list associated with the key
    my_dict[key].append(value)
>>> my_dict
defaultdict(<class 'list'>, {'even': [0, 2, 4], 'odd': [1, 3]})

It did not need to check if the key existed in the python dictionary before adding to the list.

5. Update Dictionary

To update a dictionary value, all that is needed to be done is to pass a new value to the key you want to update the value for.

>>> my_dict = {}
>>> my_dict['San Diego'] = 'USA'
>>> my_dict['San Diego']
>>> 'USA'
>>>
>>> # update value for key "San Diego"
>>> my_dict['San Diego'] = 'United States of America'
>>> my_dict['San Diego']
>>> 'United States of America'

6. Dictionary Comprehension

If you understood how list comprehension works, understanding dictionary comprehension should be as simple as it.

For example, below we can create a dict where the key is number and the value is the square of the number.

>>> my_dict = {n: n ** 2 for n in range(10)}
>>> my_dict
>>> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

It is also simple to add a condition within the dict comprehension. The condition here only processes even numbers.

>>> my_dict = {n: n ** 2 for n in range(10) if (n % 2) == 0}
>>> my_dict
>>> {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

7. Dictionary Sort

As a dictionary has a key and a value, we can sort it in two ways:

7.1 Dictionary sort by key

We can simply sort the keys of a dict by using the method sorted() which will sort the keys and them allow us to have access to the keys in sorted order.

>>> my_dict = {}
>>> 
>>> my_dict['Tokyo'] = 'Japan'
>>> my_dict['San Diego'] = 'USA'
>>> 
>>> for city_name in sorted(my_dict):
>>>     print(city_name, my_dict[city_name])

Prints

# sorted
>>> San Diego USA
>>> Tokyo Japan

If we had not added the sorted() method, it would have printed as below because the key “Tokyo” was the first one to enter the dict.

# not-sorted
>>> San Diego USA
>>> Tokyo Japan

7.2 Dictionary sort by value

In Python 3.6+, you can sort the dictionary by value using a dictionary comprehension.

>>> my_dict = {"Tokyo": 2 , "Rio de Janeiro": 3, "San Diego": 1}
>>> my_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
>>> my_dict
>>> {'San Diego': 1, 'Tokyo': 2, 'Rio de Janeiro': 3

More Resources

Here are three of my favorite Python Books in case you want to learn more about it.

Related Posts