In this article, we will discuss different ways to create dictionary objects in python.

What is a dictionary?

dictionary is an associative container that contains the items in key/value pairs.  For example, we if want to track the words and their frequency count in an article like,

“Hello” occurs 7 times
“hi” occurs 10 times
“there” occurs 45 times
“at” occurs 23 times
“this” occurs 77 times

We can use the python dictionary to keep this data, where the key will the string word and value is the frequency count.

Now let’s see different ways to create a dictionary,

Creating Empty Dictionary

We can create an empty dictionary in 2 ways i.e.

It will create an empty dictionary like this,

Creating Dictionaries with literals

We can create a dictionary by passing key-value pairs literals i.e.

It will create a dictionary like this,

Creating Dictionaries by passing parameters in dict constructor

We can create a dictionary by passing key-value pairs in dictionary constructor i.e.

It will create a dictionary like this,

Creating Dictionaries by a list of tuples

Suppose we have a list of tuples i.e.

We can create a dict out of this list of tuple easily by passing it in constructor i.e.

It will create a dictionary like this,

Creating a Dictionary by a list of keys and initializing all with the same value

Suppose we have a list of string i.e.

Now we want to create a dictionary where all the elements of the above list will be keys and their default value is 0.
We can do that using fromkeys() function of dict i.e.

It will Iterate over the list of string and for each element, it will create a key-value pair with value as default value provided and store them in dict.

It will create a dictionary like this,

Creating a Dictionary by two lists

Suppose we have two lists i.e.

List of strings,

List of integers,

Now we want to use elements in the list of string as keys and items in the list of ints as value while creating a dictionary.
To do that we are going to use zip() function that will Iterate over the two lists in parallel.

For each entry in the list, it will create a key-value pair and finally create a zipped object. Now, we can pass this zipped object to dict() to create a dictionary out of it i.e.

It will create a dictionary like this,

Learn more about Dictionaries in Python,

The complete example is as follows,

Output:

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,