6 Ways to initialize a Dictionary in Python

sokacoding
5 min readJan 24, 2023

--

Hello fellow Coders!

As a reminder for beginners: A dictionary in Python is a collection of key-value pairs, where each key is unique. Dictionaries are enclosed in curly braces. We will explore 6 options for creating dictionaries. Consider the following data that we wish to store in a dictionary.

Curly braces & key-value pairs

The technique shown in the following example is the most common one for creating dictionaries. Use curly braces and write your keys and values separated by a colon. Separate the key-value pairs by a comma.

# One possible way of creating a dictionary
my_dict = {'A':42, 'B': 'Hello', 'C': [1, 4, 20]}
# Accessing a dictionary
print(my_dict['A'])
>>> 42
print(my_dict['B'])
>>> Hello
print(my_dict['C'])
>>> [1, 4, 20]

This approach allows for flexibility in key types. You can use every hashable python object as a key such as an integer, float, boolean, string or even tuple. Using types other than strings is rather uncommon, but it is good to have the option for special cases. I recommend this method if the dictionary is introduced with little data at the beginning.

The dict() constructor

Instead of using curly braces, you write all your arguments inside the dict() constructor, replace the colons with equal signs and write your keys without quotation marks.

my_dict = dict(A=42, B='Hello', C=[1, 4, 20])

However, this approach has one disadvantage compared to the first one. Here you are restricted to using alphanumerical keys starting with a letter.

# Works
my_dict = {1:'first value', 2:'second value'}
print(my_dict[1])
>>> first value

# Syntax Error!
my_dict = dict(1='first value', 2='second value')
>>> SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

The dict() constructor with a list of tuples of key-value pairs

Another option is to put a list of tuples of key-value pairs into the constructor.

my_dict = dict([('A', 42), ('B', 'Hello'), ('C', [1, 4, 20])])

If your list contains many elements, you can assign it to a variable beforehand.

my_list = [('A', 42), ('B', 'Hello'), ('C', [1, 4, 20])]
my_dict = dict(my_list)

Using this option is also a workaround for the restriction we just mentioned. As with the first option, you can now use any hashable object as a key again.

# Syntax Error!
my_dict = dict(1='first value', 2='second value')
>>> SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

# Works
my_list = [(1, 'first value'), (2, 'second value')]
my_dict = dict(my_list)
print(my_dict[2])
>>> second value

The zip() function inside the dict() constructor

We know that we can use a list of tuples. If we have two lists of equal length, one containing the desired keys and the other the corresponding values, we can combine them using the zip() function.

keys = ["A", "B", "C"]
values = [42, "Hello", [1, 4, 20]]
my_dict = dict(zip(keys, values))

Choose this method if you want to create two separate lists with keys und values and intend to use the dictionary at a later stage due to the program design.

Dictionary comprehension

Inside curly braces, we can make use of dictionary comprehension. This approach is used rather differently compared to our first examples where we have the data ready to be used. With dictionary comprehension, you can calculate desired values while creating the dictionary. Suppose we want to create a dictionary in which we want to assign each number from a list to its square.

my_numbers = [1, 2, 3, 4]
my_dict = {num: num**2 for num in my_numbers}
print(my_dict)
>>> {1: 1, 2: 4, 3: 9, 4: 16}

Furthermore, we can even work with conditions. Let us modify the dictionary so we only use key-value pairs where the value of the squared number is bigger than 5.

my_numbers = [1, 2, 3, 4]
my_dict = {num: num**2 for num in my_numbers if num**2 > 5}
print(my_dict)
>>> {3: 9, 4: 16}

For the sake of completeness, I show you how to use dictionary comprehension if we have a list of tuples with our sample data to initialize a dictionary. Of course, you would use this list within the dict() constructor and be done right away.

my_list = [('A', 42), ('B', 'Hello'), ('C', [1, 4, 20])]
my_dict = {key:value for key, value in my_list}

The dict.fromkeys() method

In this example, we won’t use the my_dict data because this method is about assigning a default value to known keys. Let’s assume we want to assign the string 'default' to the keys provided. We can do it using the dict.fromkeys() method like this.

keys = ['A', 'B', 'C']
my_dict = dict.fromkeys(keys, 'default')
print(my_dict)
>>> {'A': 'default', 'B': 'default', 'C': 'default'}

If no default value is specified then None is being assigned to the keys.

keys = ['A', 'B', 'C']
my_dict = dict.fromkeys(keys)
print(my_dict)
>>> {'A': None, 'B': None, 'C': None}

But be careful! Suppose you want to assign empty lists to your keys you cannot use this method! All keys will be assigned an empty object list with the same id. Meaning the following will happen.

keys = ['A', 'B', 'C']
my_dict = dict.fromkeys(keys, [])
print(my_dict)
>>> {'A': [], 'B': [], 'C': []}

# Trying to append 42 only to the list assigned to key 'A'
my_dict['A'].append(42)
print(my_dict)

# 42 got appended to every key as it is the same list
>>> {'A': [42], 'B': [42], 'C': [42]}

This would be another use case for dictionary comprehension.

keys = ['A', 'B', 'C']
my_dict = {key: [] for key in keys}
print(my_dict)
>>> {'A': [], 'B': [], 'C': []}

# Trying to append 42 only to the list assigned to key 'A'
my_dict['A'].append(42)
print(my_dict)

# 42 was appended exclusively to the list assigned to key 'A'
>>> {'A': [42], 'B': [], 'C': []}

Conclusion

Dictionaries in Python are a powerful and versatile data structure that can be created in several ways. I hope that this article has given you a comprehensive overview of the different ways to initialize a dictionary in Python. Thanks for reading and feel free to drop a comment!

--

--

sokacoding
sokacoding

Written by sokacoding

M.Sc. Media Informatics. Scientific Associate at Hochschule Düsseldorf - University of Applied Sciences.

No responses yet