Courses Enquiry

Python Dictionary

1 min 37 sec read


The Python dictionary is similar to Map in Java or objects with key-value pairs in Javascript. Dictionary is a collection that is unordered, changeable, and indexed. No duplicate members are allowed in the python dictionary.

Example of Dictionary and how to use it

# Dictionary = key : value

# Create a dictionary
d = {"dog" : "bark", "cat" : "meow" }

# Print the type of the variable
print(type(d))

# Print the contents of the dictionary
print(d)

# Get the entry from a dictionary using the key
print(d["cat"])

# KeyError....snakes is not a key in our dictionary 
print(d["snakes"])

# Check if a dictionary has a given key
print("cat" in d)
print("lion" in d)

# Add an element in a dictionary
d["lion"] = "roar"
print(d)

# Delete an element from a dictionary
del d["lion"]
print(d) 

More about Dictionaries

Given a key, get its value from the dictionary. If the key is not in the dictionary, you can specify the default value as well. In this example, the lion is not in the dictionary so the output will be NA. You can assign a default value if the key is not present in dictionary print(d.get('lion', 'Not in the dictionary'))

# Create a dictionary
d = {"dog" : "bark", "cat" : "meow" }
print(d.get("cat"))
print(d.get("lion"))
print(d.get("lion", "Not in the dictionary"))
print(d.get("lion", "NA"))
print(d.get("dog", "NA")) 

Looping through Dictionary

You can loop through a dictionary using two ways,

Way 1

colg = {"Mahanadi" : 350, "Ganga" : 300, "Jamuna" : 400}
for hostel in colg:
 rooms = colg[hostel]
 print("Number of rooms in %s hostel = %d" % (hostel, rooms))
 print(" ") 

Way 2

colg = {"Mahanadi" : 350, "Ganga" : 300, "Jamuna" : 400}

# Using built-in items() method
print("*********** Using built-in items() method **************** ")
for hostel, rooms in colg.items():
 print("Number of rooms in %s hostel = %d" % (hostel, rooms)) 

Dictionary Comprehension

For example, say you want to know the animal which makes the sound meow. We can do this fairly simply using python dictionary comprehension.

d = {"dog" : "bark", "cat" : "meow" } 
k = [k for k, v in d.items() if v == "meow"]
print(k) 

k,v indicates key-value pairs in dictionary d. If the dictionary items contain value meow then the given program prints the key for the specified value.

Unlock learning opportunities with our expert-led coding courses.
Real-time doubt solving in a live online coding class is also available in the course
that will help you to stay connected with an experts while learning.

Browse Online Coding Classes Videos