[Python] Creating Dictionaries

Nikhil Narayanan
2 min readApr 11, 2020

--

A dictionary is one of the data structures in Python that stores data as a key — value pair. Storing of the key’s are completely unordered unlike what we have in Python lists. Since data is unordered, there is no mechanism to index them and retrieve data like we did in list. Most importantly, the data is mutable, which mean, I can manipulate or change data (value) for a particular key.

Through this article, we will discuss, how to create dictionaries in Python. Is there just one method to create? or are there many more ways to create a dictionary in Python. Let’s find out..!!

Creating dictionary using { }

This is one of the common way to create an empty dictionary in Python. We just create a variable to assign this curly brackets to it, because in Python dictionaries are written in curly brackets ({}).

Is it possible to create my dictionary with values in it, other than just using curly brackets. This is possible. Let see how we can do this

Above snippet shows 4 things :-

  1. How create / initialise an empty dictionary
  2. How to create a dictionary with values in it
  3. A dictionary with multiple types of values, — strings, list and even dictionaries

Dictionary using dict( ) method

dict() is a built in method in Python dictionaries. Using this built in method, we can create and even copy one dictionary to other. This is how it works,

In this, we can see dict() method takes in any keyword arguments that we pass in. So it is something like a constructor dict(**kwargs) .

Also, we can see how a list of tuples can be converted to a dictionary easily using the dict() built in method

Creating using zip( )

I have 2 list in with me of the same length, is there any way to create a dictionary out of it? Yes, we can achieve this using zip() function. Here is how we can do this,

These are some of the ways we can create or initialise a dictionary in Python, hope this helps you in coding.

Thanks for reading, Have a nice day ..!!

--

--

Nikhil Narayanan

DevOps Engineer | Python Developer | Machine Learning | Artificial intelligence Enthusiast