Understand Python Dictionary (key-value pair / Hash Map)

This tutorial is about Python dictionary which is data-structure representing  key-value pairs, you can also call it a HashMap.

One of the very common use of hashmap is finding frequency of characters in a string

Basically a dictionary is like a list but instead of integer index it can be of any type
to define a dictionary we use a key-value pair with a colon between them.

in the example below, “one” maps to 1

also note that a dictionary is un-ordered, it may not show the items in the order it was defined. 

Creating and accessing a Dictionary

>>> my_dict = {"one":1,"two":2,"three":3}
>>> my_dict
{'three': 3, 'two': 2, 'one': 1} #un-ordered items
>>> my_dict["one"] #we are using a string as an index
>>> my_dict["two"]
>>> my_dict["three"]3

we can also create an empty dictionary and add items to it later.

>>> my_dict = {}
>>> my_dict["one"] = 1
>>> my_dict["two"] = 2
>>> my_dict["three"] = 3
>>> my_dict
{'three': 3, 'two': 2, 'one': 1}
>>> my_dict["one"]1
>>> my_dict["two"]2
>>> my_dict["three"]3

Take user input in a Dictionary

n=int(input("Enter max items for the dictionary"))
for i in range(n):
key=input("Enter the key: ")
value=input("Enter the value: ")

Looping Through a Dictionary

>>> for key in my_dict:
... print(key, my_dict[key])
('three', 3)
('two', 2)
('one', 1)

Check if  a particular key is present in the dictionary

>>> 'one' in my_dict
>>> 'blabla' in my_dict

You can take this Python Quiz

Leave a Reply

Your email address will not be published.