Python Dictionaries
By: Erdem Isbilen
Tags: Python3, Comprehension, Programming, Python, Python Dictionaries

Python Dictionaries

Use Python Dictionaries Like a Pro

Photo by freestocks on Unsplash

Python programming language is widely used by developers in data science projects. To complete such projects, understanding data structures plays an important role. Python has several built-in data structures such as lists, sets, tuples, and dictionaries, in order to support the developers with ready to use data structures.

In this article, I will try to explain why and when to use Python dictionaries, meanwhile giving you some hints about the correct usage of the dictionary methods.

Let’s understand the Python dictionaries in detail with step-by-step explanations and examples.

What is a Python Dictionary?

In a nutshell, a dictionary can be defined as a collection of data stored in key/value pairs. Keys must be an immutable data type (such as string, integer or tuple), while values in a dictionary can be any Python data type.

Duplicate keys are not allowed. If the same key is used twice in the same dictionary, then the last occurrence will override the first.

Data stored in a dictionary can be modified so they are called mutable objects. They are unordered which means that the order in which we specified the items is not maintained. (They are ordered in version 3.7 onwards)

As they are dynamic, they can grove or shrink when needed.

When to use Python Dictionaries?

As you now know what is a Python dictionary, it is time to explore when to use them in your code.

Here is a list helping you to understand when to use Python dictionaries;

When the data has a unique reference that can be associated with the value.

When quick access to data items is important. Dictionaries are designed to let us find a value instantly without the need for searching through the whole collection.

When the data order is not important.

As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place.

When memory consideration is not an important factor for the application. Compared to lists and tuples, dictionaries take up more space in memory.

How to Create a Python Dictionary?

There are many ways of creating and initializing the dictionaries. As shown in the below code snippet, the easiest way of creating dictionaries is using curly brackets or dict() method directly;

If you have two iterable objects (for example list objects), you can use zip() function to create a dictionary. See the example below;

fromkeys() method is another way of creating dictionaries. It takes an iterable object and creates a dictionary with specified value as shown in the below code snippet;

What is a Python Dictionary Comprehensions?

Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic. They shorten the code required in dictionary initialisation and they can be used to substitute ‘for’ loops.

The general syntax for dictionary comprehensions is:

dictionary = {key:value for (key, value) in iterable}

Adding Conditionals to a Dictionary Comprehension

You can extend the use of dictionary comprehensions with conditional statements. You can see below the use of multiple ‘if’ conditionals, ‘else-if’ conditionals in dictionary comprehensions;

Time Complexity of Dictionary Operations

Getting, setting and deleting an item in a dictionary has O(1) time complexity which means that no matter how big is your dictionary, the time it takes to access an item is constant.

Iterating over a dictionary has O(n) time complexity means that the time it takes to perform this task linearly proportional to the number of items contained in the dictionary.

How to Access Values in a Dictionary

If you try to access an element with a key which does not exist in your dictionary, you get a KeyError. Knowing the proper way of accessing the elements inside the dictionary is important for not to have KeyErrors during runtime.

To avoid the KeyError, access the elements of a dictionary with get() method. Alternatively, you can check the existence of the key with ‘in’ keyword.

How to Insert an Item Into a Dictionary?

There is no add() , insert() or append() methods that you can use to add items into your dictionary. Instead, you have to create a new key to store the value in your dictionary. If the key already exists in the dictionary, then the value will be overwritten.

Below code snippet shows many examples of adding items into your dictionary;

What are the Dictionary methods?

There are many methods contained in the Python dictionaries helping you to perform different tasks on the dictionary objects. I listed them below with their short definitions;

popitem() : Remove the last item from the dictionary

: Remove the last item from the dictionary pop(key, defaultvalue) : Removes and returns an element from a dictionary for the given key

: Removes and returns an element from a dictionary for the given key keys(): Return the keys

Return the keys values(): Return the values

Return the values items(): Return the dictionary’s key-value pairs

Return the dictionary’s key-value pairs get(key[, value]): Returns the value for the specified key if the key is in a dictionary

Returns the value for the specified key if the key is in a dictionary fromkeys(keys, value): Returns a dictionary with the specified keys and the specified value

Returns a dictionary with the specified keys and the specified value setdefault(key, value) : Returns the value of the item with the specified key. If the key does not exist, inserts the key with the specified value

: Returns the value of the item with the specified key. If the key does not exist, inserts the key with the specified value update(iterable) : Inserts the specified items to the dictionary if the key is not in the dictionary, otherwise it updates the value

: Inserts the specified items to the dictionary if the key is not in the dictionary, otherwise it updates the value copy(): Returns a shallow copy of the dictionary

Returns a shallow copy of the dictionary clear(): Removes all items from the dictionary

How to Remove an Item From a Dictionary?

To remove an item from a dictionary object, you can use ‘del’ keyword or pop() method. In addition, you can use dictionary comprehensions to remove items of a dictionary. Check below code snippet for the implementation of those methods with examples;

How to Copy Dictionaries?

You can use the copy() method to get a shallow copy of an existing dictionary. A shallow copy means a new dictionary will be populated with references to the objects in the existing dictionary.

To create a deep copy, ‘copy.deepcopy(dict)’ method should be used. It creates a fully independent clone of the original dictionary with all of its elements.

See below to understand how you can implement shallow copy and deep copy methods on dictionary objects;

How to Merge Dictionaries?

You can merge dictionaries with a custom function containing dict.copy() and dict.update() methods.

In Python 3.5 and onwards, you can merge dictionaries with unpacking them using ‘**’ operator.

The simplest and easiest way of merging dictionaries is using the merging operator ‘|’ which is available in Python 3.9+

Below code snippet shows implementations of all above methods with examples;

How to Sort Items In a Dictionary?

Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering. To preserve the ordering, we can store the sorted dictionary in an OrderedDict

See below to explore how you can sort the dictionaries by key and by value;

How to Loop Through a Dictionary?

Python dictionary methods; values(), keys(), and items() provide access to the elements contained inside a dictionary. You can use them in for loops to iterate through the dictionaries.

In addition, dictionary comprehensions can also be used for iteration as shown below;

Conclusion and Key Takeaways

As data structures are fundamental parts of our programs, it is really important to have a solid understanding of Python dictionaries to create efficient programs.

I explained why and when to use the dictionaries, some of the key takeaways are listed below;

Python dictionaries can be used when the data has a unique reference that can be associated with the value .

that can be associated with the . As dictionaries are mutable , it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place.

are , it is not a good idea to use dictionaries to store data that shouldn’t be modified in the first place. Python dictionaries are unordered up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering.

up to version 3.7 so even if you sort the (key, value) pairs, you wouldn’t be able to store them in a dictionary by preserving the ordering. Python dictionary comprehensions provide an elegant way of creating dictionaries. They make your code easier to read and more Pythonic.

Thank you for reading!