Skip to Content

How To Initialize A Dictionary In Python

How To Initialize A Dictionary In Python

How do you initialize an empty dictionary in Python? Is it best to use dict() or {}?

There are two common ways of initializing a dictionary in Python. One involves using the built-in function dict() and is known as the dict constructor, whereas the other method is known as dict literal and has the syntax {}.

Here’s an example demonstrating how to initialize using both approaches in the Python REPL:

>>> my_dict = dict()
>>> print(my_dict)
{}
>>> my_dict_literal = {}
>>> print(my_dict_literal)
{}

As you can see from the examples above there’s no difference in what is produced when intializing an empty dictionary.

The difference comes when you’re looking to intialize your dictionary with something.

Difference Between Dict Literal And Dict Constructor

If your dictionary is to be pre-populated with something when it is initialized then you might find it easier to use the dict literal approach as you already have your list of key: value pairs.

>>> my_dict_literal = {'a': 1, 'b': 2, 'c': 3}

However, if the data you need to populate your dictionary variable is in another format then the dict constructor may be a better fit with the data you’re pre-populating your dictionary with.

Here are some examples where the dictionary variable is using data of a different type to initialize the dictionary:

>>> my_dict = dict(a=1, b=2, c=3)
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
>>> my_dict = dict([('a', 1), ('b', 2), ('c', 3)])
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
>>> my_dict = dict([['a',1], ['b',2], ['c',3]])
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}

As you can see from the above examples there are a variety of ways to initialize a dictionary with values.

Convert Two-Dimensional List To List Of Dictionaries (One-Liner)

This dict constructor can help when trying to translate a two-dimensional list into a list of dictionaries. If you have a 2D list in Python and the first row lists all the column headings with all the subsequent data rows underneath then the first thing you need to do is to translate your 2D list such that each column heading is aligned to each row’s cell.

So if you have the following two-dimensional list:

[['Employee', 'Year', 'Salary'], ['Joe', 2022, 120000], ['Mary', 2022, 150000], ['Scott', 2022, 180000]]

It needs to change to a format for each row where the key and value are more closely aligned:

[[['Employee', 'Joe'], ['Year', 2022], ['Salary', 120000]], 
 [['Employee', 'Mary'], ['Year', 2022], ['Salary', 150000]], 
 [['Employee', 'Scott'], ['Year', 2022], ['Salary', 180000]]]

Here’s how by using a list comprehension and the built-in zip() function on how you can create a list of dicts from a two-dimensional list, using the dict constructor:

>>> my_2d_list = [['Employee', 'Year', 'Salary'], ['Joe', 2022, 120000], ['Mary', 2022, 150000], ['Scott', 2022, 180000]]
>>> my_dict = [dict(zip(my_2d_list[0], x)) for x in my_2d_list[1:]]
>>> print(my_dict)
[{'Employee': 'Joe', 'Year': 2022, 'Salary': 120000}, {'Employee': 'Mary', 'Year': 2022, 'Salary': 150000}, {'Employee': 'Scott', 'Year': 2022, 'Salary': 180000}]

As you can see from the output above I have achieved the desired result of converting a two-dimensional list to a list of dicts.

Let me explain the list comprehension line: [dict(zip(my_2d_list[0], x)) for x in my_2d_list[1:]] by breaking it up into pieces.

I’ll start from the end of the code and work my way to the front.

First, the one-liner for loop for x in my_2d_list[1:] helps to loop through each row in the original two-dimensional list. As the two-dimensional list contains a row of column headings (the first row) you can exclude this from the loop by starting from the second row. This is enumerated by using the slice operator my_2d_list[1:] which gets every row after the first. The slice operation performed starts at the second element (which has an index of 1) and gets all other elements to the end.

Second, the code in front of the for loop seen with the following: dict(zip(my_2d_list[0], x)) contains the familiar dict constructor, but inside has a zip() function which contains two parameters: the first row of the two-dimensional list and each row from the for loop.

What does the zip() function do?

The built-in zip() function takes a series of iterables, such as two lists, and produces a tuple with an item from each one.

Therefore, in my working example, the zip() function will take the first item in the first list (being the column header row) and then take the corresponding first item in the row x being passed in from the for loop.

The result is a list of tuples containing the header item and the corresponding cell in each row.

This function is perfect for what is needed in being able to produce a list of dictionaries.

Finally, to wrap everything up into a list the entire expression is wrapped in a list to produce the needed list of dictionaries.

Here’s how this formula would look based on what I’ve explained above and using it for your purposes:

[dict(zip(header_row, x)) for x in my_list[1:]]

Summary

Choosing whether to initiate a variable with a dict literal or dict constructor would depend upon whether you need to convert an existing element into a dictionary, or whether you would prefer to start with an empty dictionary and populate it as you go.

The handy functionality of the dict constructor is that it can be handy when converting something like a two-dimensional list into a list of dictionaries using the one-liner code [dict(zip(my_list[0], x)) for x in my_list[1:]].