LEC9 Python Dictionory
LEC9 Python Dictionory
Python
Sub Code:18EC552
Girija.S
Assistant Professor
Dept. of ECE
Dr.AIT
Objectives
A dictionary is a collection of key-value pairs subject to the constraint that all the keys should
be unique
A dictionary organizes information by association, not position
Creating a Dictionary
Consider building a dictionary that maps from English to Spanish words, so the
keys and the values are all strings
>>> eng2sp
{'one': 'uno'} # a key-value pair with a colon between
the key and value
>>> eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'} #The order of the key-value
pairs is not the same. the order of items in a
dictionary is unpredictable
Accessing Dictionary Elements
>>> D[‘apple’]
‘red’
grapes
grapes
apple apple
Iterating Through the Values of a Dictionary
The dict.values() returns a view of all the values in the dictionary
D = { 'grapes' : 'green' , 'apple' : 'red' }
V = D.values()
for i in V:
print(i)
green
red
It is possible to iterate through the keys and print out the corresponding values
for K in D:
print(D[K])
green
red
Iterating Through the Key-Value Pairs
The dict.items() returns the key-value pair (each pair as a tuple) in the
dictionary
grapes green
apple red
Deleting Elements From Dictionary
>>> D = { 'grapes' : 'green' , 'apple' : 'red' }
>>> D.popitem() # remove an element from the dictionary and return the
pair in the form of tuple
( 'grapes‘, 'green‘)
>>> D.popitem()
KeyError: 'popitem(): dictionary is empty'
Program Based on Dictionaries
# program to display the capital of a country