position: fixed; top: auto !important; margin-left: 112px;

Python Dictionary

The python dictionary is similar to Map in Java or objects with key-value pairs in Javascript. Dictionary is a collection which 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, lion is not in the dictionary so output will be NA. You can assign default value if 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('\n')

Way 2

colg = {'Mahanadi' : 350, 'Ganga' : 300, 'Jamuna' : 400} # Using built-in items() method print('*********** Using built-in items() method ****************\n') 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.


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.