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

4 Must-Know Features of Python Dictionaries

Boost your scripts by using dictionaries more efficiently

Photo by Element5 Digital on Unsplash
Photo by Element5 Digital on Unsplash

Data structures are the key components of programs. They hold or contain the data in a particular way to make the programs work more efficiently. How to access the data stored in a data structure is of crucial importance as well.

Dictionaries are one of the core data structures in Python. A dictionary contains key-value pairs. A value can easily be accessed via its key. Here is a simple example:

members = {1001: "John", 1002: "Jane", 1003: "Emily"}
print(members[1001])
John

In this article, we will go over 4 must-know features of Python dictionaries. They are essential for using dictionaries efficiently and appropriately.


  1. Dictionaries are unordered

A dictionary contains key-value pairs but does not possess an order for the pairs. Thus, a more precise definition is that a dictionary is an unordered collection of key-value pairs.

As a result, we cannot perform typical operations associated with the order of items. For instance, it is not possible to get the first or last item in a dictionary.

Another common operation done with numeric indices is slicing. It can be performed on a Python list:

mylist = ["John", "Jane", "Emily"]
print(mylist[0])
John
print(mylist[1:])
['Jane', 'Emily']

Unlike lists, dictionaries are indexed by keys. Thus, it is not possible to do these operations on dictionaries due to not having an order. We can access a value by passing its key in square brackets or the get method.

members = {1001: "John", 1002: "Jane", 1003: "Emily"}
members[1001]
'John'
members.get(1001)
'John'

It is important to note that lacking an order is not a deficiency of Python dictionaries. In fact, it can be considered as a strength. They allow for quickly accessing and retrieving information associated with a particular key.


  1. Keys are unique

Dictionary keys must be unique. It makes sense because we use them for accessing values. Having duplicated keys defeats the purpose of using a dictionary to store information.

Although a dictionary does not allow for creating duplicated keys, it does not warn you if you use the same key multiple times. Thus, you need to be extra careful not to cause any unexpected behavior.

Let’s go over a few examples to make it more clear.

members = {1001: "John", 1002: "Jane", 1003: "Emily", 1001: "Max"}
print(members)
{1001: 'Max', 1002: 'Jane', 1003: 'Emily'}

We use the same key (1001) twice but does not get any error. Instead, Python overwrites the previous value with the new one.

The same behavior is observed when updating a dictionary. We can add a new item to a dictionary as below:

members[1004] = "Ashley"
print(members)
{1001: 'Max', 1002: 'Jane', 1003: 'Emily', 1004: 'Ashley'}

The key 1004 was not in the members dictionary so it is added with the given value. If we use the same method and pass a key that is already in the dictionary, its value is updated.

members[1001] = "AAAAA"
print(members)
{1001: 'AAAAA', 1002: 'Jane', 1003: 'Emily', 1004: 'Ashley'}

Thus, it is more like updating the value of a key rather than creating a new key-value pair.


  1. Keys must be immutable

Dictionary keys must be of an immutable type. Strings and numbers are the two most commonly used data types as dictionary keys. We can also use tuples as keys but they must contain only strings, integers, or other tuples.

We have already created a dictionary with integer keys. Let’s create a couple of more with string and tuple keys.

# string keys
dict_a = {"Param1": "value1", "Param2": "value2"}
print(dict_a)
{'Param1': 'value1', 'Param2': 'value2'}

# tuple keys
dict_b = {(1, 10): "value1", (1,20): "value2"}
print(dict_b)
{(1, 10): 'value1', (1, 20): 'value2'}

If we try to create a key of a mutable (i.e. unhashable) type, a type error is raised.

dict_c = {[1, 2] : "value1", [1,4]: "value2"}
TypeError: unhashable type: 'list'
dict_d = {(1, [1,2]): "value1"}
TypeError: unhashable type: 'list'

  1. Dictionary comprehension

There are several methods to create a dictionary in Python. One method is writing key-value pairs in curly braces like we have done up to this point.

Another option is the dict constructor which creates a dictionary from a sequence of key-value pairs.

sequence = [[1, "John"], [2, "Jane"]]
dict(sequence)
{1: 'John', 2: 'Jane'}

Dictionary comprehension is similar to the concept of list comprehension. It is more practical way of creating dictionaries that contain a structured set of values.

Consider we have the following text.

text = "By 1908, Einstein was recognized as a leading scientist and was appointed lecturer at the University of Bern"

We want to get an overview of the length of the words in this text. We can create a dictionary that contains both the words and their lengths. Dictionary comprehension accomplishes this task simply as follows:

dict_a = {x: len(x) for x in text.split(" ")}

We split the text at the space characters and use each word as a key. The values are calculated calling the built-in len function on the words.

(image by author)
(image by author)

It is worth emphasizing that we do not get any information as to the number of occurrences of the words in the text. The dictionary consists of unique words.


Conclusion

Dictionary is a very important data structure in Python. They are sometimes called "associative arrays" in other Programming languages. They allow for quickly retrieving information about an entry. Let’s make an analogy to demonstrate the use of dictionaries.

Consider an address book without any organizational structure. When a new item is added, it is written at the end. In order to lookup an address in this book, you would start reading from the beginning. In you are not lucky, you might have to read until the end to find what you are looking for.

If this address book had a separate section for each letter and addresses were stored according to their initial letters, it would be much easier to find an address. Dictionaries provide such an easy lookup. We give them the key, and they return the associated value.

Thank you for reading. Please let me know if you have any feedback.


Related Articles