The world’s leading publication for data science, AI, and ML professionals.

Python Beginner Breakthroughs (Dictionaries)

One data type that is incredibly versatile for data science work and provides tons of utility is the dictionary, allowing a built-in…

Photo by Pisit Heng on Unsplash
Photo by Pisit Heng on Unsplash

A confession I have is that prior to Learning about Python and computer science in general, I had no idea that such a data type existed. When I finally was exposed to it and got to see the extreme amounts of potential that it has, dictionaries quickly became one of the data types that I admired for their structure and versatility. This article will aim to provide a quick overview of what dictionaries are, general rules about how they are to be used, practical ways to use them, and then some quick hypothetical examples of where they can be used.

Commonly referred to in other programming languages as "associative memories" or "associative arrays", the key principle that the dictionary serves is to map two variables through a parent-child relationship. In this relationship, the parent, syntactically known as the key, and the child, known as the value, represent a key-value pair in the datatype. The most common usage of the dictionary is to have a set of keys that can be called upon and then produce the matching values associated with that key.

The below image is a basic example of a dictionary of some US States and cities representing the key and value pairs. Note that for each value there is a distinct key-value pair that it is connected to.

Visual representation of a dictionary with some US States (as keys) and Cities (as values of the keys). Image by Author
Visual representation of a dictionary with some US States (as keys) and Cities (as values of the keys). Image by Author

Rules for Dictionaries:

There are some basic rules to be aware of when using dictionaries, that will make the learning curve on using them less steep.

  • Dictionary keys can be any immutable type, such as strings, numbers, or tuples (Note: tuples that contain immutable objects are not acceptable as keys)
  • A dictionary itself is mutable, meaning that you can make changes (add/delete/alter) to the item upon creation
  • Duplicate keys cannot exist in a dictionary since the dictionary itself is indexed across its keys. If you assign a value to an already existing key you will overwrite the previous value.
  • Since dictionaries are indexed across their keys you cannot use list (sequence-based) commands such as .append & .extend or slice across the keys
  • The order of items is preserved (since indexing is done across the keys), new items are added to the end. This is true as well when items are deleted.
  • Dictionaries can be nested to provide additional relationships between two separate items (or dictionaries)

How to … with Dictionaries:

Build Dictionaries

Items can be added using the dict() function as seen below where you define the key and value pair almost like a tuple.

d = dict([
    (<key>, <value>),
    (<key>, <value),
      .
      .
      .
    (<key>, <value>)
])

Another powerful way to build a dictionary is by using comprehensions. I have another article that goes over the list comprehension logic and construction and those same ideas can be applied to dictionaries. You can find the list comprehension article here.

As you can imagine, just like with lists, there are multiple methods of building lists like iterating across sequences or ranges.

Iterate Across a Dictionary

You can iterate through dictionaries in a variety of ways and particular methods will allow you to access or call, the desired keys, values, or key-value pair. The simplest method is to simply iterate using a for loop of the dictionary as shown below.

a_dict = {'a': '1', 'b': '2', 'c': '3'}
for key in a_dict:
    print(key)
...
a
b
c

There are 3 particularly powerful methods built into the Python dictionary type that will allow for targeted iterations, based on what you want to pull out of the dictionary. The methods are: .keys(), .values(), .items()

So you want the Keys?

  • .keys() method returns just the keys of a dictionary an example of how to use it is below. Notice that it is similar to just iterating through the dictionary
a_dict = {'a': '1', 'b': '2', 'c': '3'}
for key in a_dict.keys()
    print(key)
...
a
b
c

So you want the keys and values as a pair?

  • .items() method returns the view object of the key-value pair represented as a tuple. Notice below the use of the method and the resulting output as tuple pairs as (key, value). Notice the syntax in the second example as well.
# .items() Example 1
a_dict = {'a': '1', 'b': '2', 'c': '3'}
for item in a_dict.items()
    print(item)
...
(a,1)
(b,2)
(c,3)
# .items() Example 2
a_dict = {'a': '1', 'b': '2', 'c': '3'}
for keys, value in a_dict.items()
    print(key, value)
...
(a,1)
(b,2)
(c,3)

So you only want the values?

  • The last dictionary specific method is used to call the values of the dictionary and is the .values() method. Similarly, pay attention to the method call and the output
a_dict = {'a': '1', 'b': '2', 'c': '3'}
for value in a_dict.values()
    print(value)
...
1
2
3

How to Filter a dictionary?

Conditional logic with the appropriate method can be used in conjunction to build a new dictionary as desired from the conditions set forth. In the example below the new dictionary is filtered based on the condition relating to the values.

a_dict = {'a': '1', 'b': '2', 'c': '3'}
new_dict = {}
for key, value in a_dict.items():
    if value <= 2:
        new_dict[key] = value

new_dict
{'a':1, 'b':2}

Want to do Some Calculations Based on Dictionary Items?

The combination of utilizing the proper method and then conditional logic again will allow you to perform calculations based on the items that are contained in the dictionary. Below is an example of a dictionary of toys and their prices and it is very easy to find out the total value of all the items in the dictionary using methods and conditions.

toy_price_dict = {'toy car': '100.00', 'toy boat': '200.00', 'toy train': '300.00'}
total_cost = 0
for value in toy_price_dict.values():
    total_cost += value

total_cost
600.0

Of course, this is a pretty simple example and much more complex calculations can be done but this is the basic structure of how you would do it.

How to sort a dictionary?

Sorting is easy with dictionaries using the built-in sorted() function. Sorting can be done by sorting keys or values and is displayed in the example below. The second example of sorting through the dictionary is another way, but using a helper function to define a key by which to sort. Also, note that in the second example you can reverse the order of sorting by using the ‘reverse’ argument set to True.

# Sorting by keys example
toy_price_dict = {'toy car': '100.00', 'toy boat': '200.00', 'toy train': '300.00'}
for key in sorted(toy_price_dict):
    print(key, '->', toy_price_dict[key])

toy boat -> 200.0
toy car -> 100.0
toy train -> 300.0
#Sorting by values example 1
toy_price_dict = {'toy car': '100.00', 'toy boat': '50.00', 'toy train': '120.00'}
for value in sorted(toy_price_dict):
    print(values)

120
100
50
#Sorting by values example 2
toy_price_dict = {'toy car': '100.00', 'toy boat': '50.00', 'toy train': '120.00'}
def by_value(item):
    return item[1]

for k, v in sorted(toy_price_dict.items(), key=by_value, reverse=True):
    print(k, '->', v)
('toy boat', '->', 50.00)
('toy car', '->', 100.00)
('toy train', '->', 120.00)

Leveling Up your Dictionaries

Utilizing nested dictionaries are even much more powerful and useful. Nested dictionaries can serve as a map of future probabilities, amongst other things. An example of this is shown below:

next_day_weather = {('sunny'): {'sunny': 0.3333333333333333, 'cloudy': 0.3333333333333333, 'rainy': 0.3333333333333333}, ('rainy'): {'rainy': 1.0}, ('cloudy'): {'sunny': 0.5, 'rainy': 0.5}}

You can see here that by whatever method you predicted the probabilities of the future states, the nested dictionary can hold the future state as its key and the value as the probability. The picture below demonstrates this visually.

Visual representation of the nested dictionary in the code block. Image by Author
Visual representation of the nested dictionary in the code block. Image by Author

Hopefully, this walks through what and how dictionaries are used and will save you some searching on how to do simple tasks associated with dictionaries. If you have any questions or comments or want to see something specific, let me know as a response. Thanks.


Related Articles