How To Create A Dictionary Python?

Create A Dictionary Python

Now, after discussing some things about the dictionary, you might be curious about how we can create a dictionary. So, we are going to head into that only. We have got two ways, through which, we can create a dictionary.

Both ways are pretty easy. Let’s first discuss the first one –

In this way, you just have to give the curly brackets, in order to create a dictionary. In that dictionary, the key:value pairs would be there, and if there are multiple key:value pairs, we have to separate them with commas. Have a look at the below example, where we are trying to create a dictionary. We have used the type function, to determine the type of object that we have created.

How To Create A Dictionary?

As you can see, we could have a dictionary created for us, using the curly brackets. Later on, while considering examples, we would also put some key-value pairs in there. If you try to have a look at the output, you will find that the object is of class ‘dict’.  Let’s concentrate on another way, to create a dictionary.

In this way, we have to use the dict() constructor to create a dictionary.  This is how we are going to create a dictionary with the help of dict() constructor. We are also checking the type of object that we have created. If you try to run the above program, the output that you find is the same (<class ‘dict’>).

So, we can use the curly brackets or type constructor of dict, to create the dictionary.

Let’s now have a look at an example, through which, we can understand the syntax of a dictionary, and also, we get to add some key-value pairs to the dictionary. In the below example, we are imagining that we have a hotel, and we are keeping a record of our occupied rooms, as a dictionary, where the key is the room number, and the value of that key is the name of the person who is living in that room.

As you can see, the dictionary now has some key-value pairs over here. You can read it something like – 101 is the key, and the value corresponding to this key is ‘Mr. Gyanipandit’. So, this is what a dictionary looks like, along with some key-value pairs.

Well, now, if you want to access the value of some key, you just need that key. We are going to have a look at this later on, how can you access the values from the key? This is similar to how we access the meaning of some word in the dictionary, using the word itself.

So, if you execute the previous program, you get the dictionary printed. From python version 3.7, the dictionary is now ordered, while in earlier active versions, the dictionaries were unordered. But what do you mean by order?

It means that there is some specific order of the dictionary elements that are maintained, which will not be changed.