Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More

Article

Python Dictionary - Codzify.com

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 # = animal : sound # 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 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.

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor