12 Examples to Master Python Dictionaries | by Soner Yıldırım | Towards Data Science

Data structures are crucial parts of any programming language. In order to create robust and well-performing products, one must know the data structures very well.
In this post, we will work on an important data structure of Python programming language and that is Dictionary.
Dictionary is an unordered collection of key-value pairs. Each entry has a key and value. A dictionary can be considered as a list with special index.
The keys must be unique and immutable. So we can use strings, numbers (int or float), or tuples as keys. Values can be of any type.
Consider a case where we need to store grades of students. We can either store them in a dictionary or a list.
Using a dictionary allows us to access the grade of each student by providing the name of the student (key). On the other hand, to be able to access the grade of a particular student, we need an additional list.
The new list contains the names of the students and has the exact same order as the grades list.
Thus, a dictionary is a better choice than a list for such cases.
After this short introduction, let’s start on examples to dive deep into dictionaries. The examples will cover the features of dictionaries as well as the functions and methods to operate on them.
We can create a dictionary by providing 0 or more key value pairs between curly braces.
empty_dict = {}grades = {'John':'A', 'Emily':'A+', 'Betty':'B', 'Mike':'C', 'Ashley':'A'}grades{'Ashley': 'A', 'Betty': 'B', 'Emily': 'A+', 'John': 'A', 'Mike': 'C'}
We access a value in a list by providing the index. Similarly, in dictionaries, the values are accessed by using the keys.
grades['John']'A'grades.get('Betty')'B'
The keys method is used to get all the keys.
grades.keys()dict_keys(['John', 'Emily', 'Betty', 'Mike', 'Ashley'])
The return object is a dict_keys object which is an iterable. Thus, we can iterate over it in for loops.
Similarly, the values method returns all the values.
grades.values()dict_values(['A', 'A+', 'B', 'C', 'A'])
We cannot index on dict_keys or dict_values but we can convert them to a list and then use indexing.
list(grades.values())[0]'A'
The items method returns key-value pairs in tuples.
grades.items()dict_items([('John', 'A'), ('Emily', 'A+'), ('Betty', 'B'), ('Mike', 'C'), ('Ashley', 'A')])
Dictionaries are mutable so we can update, add or delete items. The syntax for updating or adding an item is the same. If the given key exists in the dictionary, the value of the existing item is updated. Otherwise, a new item (i.e. key-value pair) is created.
grades['Edward'] = 'B+'grades['John'] = 'B'grades{'Ashley': 'A', 'Betty': 'B', 'Edward': 'B+', 'Emily': 'A+', 'John': 'B', 'Mike': 'C'}
We can also pass a dictionary to the update function. The dictionary will be updated based on the items in the new dictionary. It will become more clear with an examples.
Consider the following grades and grades_new dictionaries:
grades = {'John':'A', 'Emily':'A+', 'Betty':'B', 'Mike':'C'}grades_new = {'John':'B', 'Sam':'A', 'Betty':'A'}
If we update grades based on grades_new, the values of John and Betty will be updated. Also, a new item (‘Sam’:’A’) will be added.
grades.update(grades_new)grades{'Betty': 'A', 'Emily': 'A+', 'John': 'B', 'Mike': 'C', 'Sam': 'A'}
We can use the del or pop function to delete an item. We just pass the key of the item to be deleted.
del(grades['Edward'])grades.pop('Ashley')'A'grades'Betty': 'B', 'Emily': 'A+', 'John': 'B', 'Mike': 'C'}
Unlike the del function, the pop function returns the value of the deleted item. Thus, we have the option to assign it to a variable.
We can iterate over a dictionary. By default, the iteration is based on keys.
for i in grades:    print(i)JohnEmilyBettyMike
We can also iterate over values (grades.values()) or key-value pairs (grades.items()).
It is similar to a list comprehension. Dictionary comprehension is a way to create dictionaries based on iterables.
{x: x**2 for x in range(5)}{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}{word: len(word) for word in ['data','science','is','awesome']}{'awesome': 7, 'data': 4, 'is': 2, 'science': 7}
The elements in the iterable become the keys of the dictionary. The values are determined based on the assignment in the dictionary comprehension.
We can create a dictionary using a list of lists or list of tuples.
a = [['A',4], ['B',5], ['C',11]]dict(a){'A': 4, 'B': 5, 'C': 11}b = [('A',4), ('B',5), ('C',11)]dict(b){'A': 4, 'B': 5, 'C': 11}
The dataframe function of Pandas can be used to create a dataframe using a dictionary. The keys become the column names and the values become rows.
Up until now, we have done examples with dictionaries whose values were strings. However, the values in a dictionary can be of any type such as lists, numpy arrays, other dictionaries and so on.
In case of creating a dataframe from a dictionary, values consist of arrays (e.g. list, numpy array).
import numpy as npimport pandas as pddict_a = {'names':['Amber','John','Edward','Emily'],         'points':np.random.randint(100, size=4)}df = pd.DataFrame(dict_a)df
The len function returns the number of items in a dictionary (i.e. the length). The clear method is used to delete all items from a dictionary so we will end up having an empty dictionary.
len(grades)4grades.clear()len(grades)0
grades = {'John':'A', 'Emily':'A+', 'Betty':'B'}dict1 = gradesdict2 = grades.copy()dict3 = dict(grades)
All dict1, dict2, and dict3 contain the exactly same key-value pairs as grades. However, dict1 is just a pointer to the key-value pairs in grades. Thus, any change in grades will also change dict1.
Dict2 and dict3 are separate objects in the memory so they will not be affected by the changes in grades.
We need to pay extra attention to how we copy dictionaries.
Python 3.9 came with merge (“|”) and update (“|=”) operators for dictionaries. I haven’t installed Python 3.9 yet so I will use the example from python documentation:
>>> x = {"key1": "value1 from x", "key2": "value2 from x"}>>> y = {"key2": "value2 from y", "key3": "value3 from y"}>>> x | y{'key1': 'value1 from x', 'key2': 'value2 from y', 'key3': 'value3 from y'}>>> y | x{'key2': 'value2 from x', 'key3': 'value3 from y', 'key1': 'value1 from x'}
Dictionaries are very important data structures in Python and used in many cases. The examples we did in this post will cover most of what you need to know about dictionaries. They will make you feel comfortable when working with dictionaries.
However, there is, of course, more to it. As with any other subject, practice makes perfect and you will master as you keep practicing.
Thank you for reading. Please let me know if you have any feedback.