Python Dictionary with Example

When we say dictionary, at first sight, what comes to our mind is that big book, that we call a dictionary. But, if I ask you why we use that dictionary, your obvious answer would be, to find the meaning of some word. So, we can say that there is some word, and associated with that word, is some meaning to that word.

Well, when we are searching for the meaning of some particular word, we are actually searching for the word itself in the dictionary, because we know that once we point to the word in the dictionary, we have the meaning associated with it there only.

Similar to this, we have a dictionary in Python as well. This dictionary is going to contain some key:value pairs. As we move ahead, we are going to further explore the dictionary now.

Python Dictionary

So, if we try to define what is a dictionary, it comes out to be something like this –

A dictionary is a collection of key-value pairs. The dictionary is ordered, and changeable, and duplicates are not allowed.

But now another question comes to our mind, what are key:value pairs? Well, we can simply consider it as there is going to be some key, and associated with that key, there is going to be some value. So, this makes a key:value pair.  Here is an insight into what are we going to cover here –

  • How to create a dictionary?
  • Adding key-value pairs to the dictionary
  • Accessing the values in the dictionary with the help of key
  • Calculating the length of the dictionary (using the len function)
  • The dictionary methods
    • The clear method (clear the dictionary)
    • The copy method (creating a copy of the dictionary)
    • The fromkeys method
    • The get method
    • The items method
    • The keys method
    • The pop method
    • The popitem method
    • The setdefault method
    • The update method
    • The values method
  • Changing the value corresponding to some key in the dictionary
  • Are duplicates allowed in the dictionary?
  • How to delete some specific element from the dictionary (or delete the dictionary itself)
  • Looping through a dictionary