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

What is a dictionary ?

dictionary is a an associative containers that contains the items in key / value pairs.  For example, we if want to track the words and thier 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 python dictionary to keep this data, where 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 a 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 Dictionary by a list of keys and initialsing all with same value

Suppose we have a list of string i.e.

Now we want to create a dictionary where all the elements of above list will be keys and thier 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 a two lists

Suppose we have two lists i.e.

List of strings,

List of integers,

Now we want to use elements in list of string as keys and items in 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,

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.