Dictionaries in Python-1

A Dictionary in Python is a collection of keys and values. Both the keys and values can be tuples.
You define a dictionary in this manner.
d={key:value,key:value…}
to create a blank dictionary use d={}
This gives great flexibility in programming. Let us look at some examples.

d1={2:”Mumbai”,1:”Jaipur”,3:”Varanasi”}
print(d1)
print(d1.keys())
print(d1.values())

Output
{2: ‘Mumbai’, 1: ‘Jaipur’, 3: ‘Varanasi’}
dict_keys([2, 1, 3])
dict_values([‘Mumbai’, ‘Jaipur’, ‘Varanasi’])

The dictionary contains two collections keys() and values().


To search for key values we use d1[key] or d1.get(key).
d1={2:”Mumbai”,1:”Jaipur”,3:”Varanasi”}

print(d1[2])
print(d1.get(1))

Output
Mumbai
Jaipur

the difference is that d1[key] will throw an exception if key is not found, whereas d1.get(key) returns None.

Sorting of keys.
d1={2:”Mumbai”,1:”Jaipur”,3:”Varanasi”}
print(d1)
sortedkeys=sorted(d1.keys())
print(sortedkeys)
for key in sortedkeys:
print (key, d1[key])

Output
{2: ‘Mumbai’, 1: ‘Jaipur’, 3: ‘Varanasi’}
[1, 2, 3]
1 Jaipur
2 Mumbai
3 Varanasi

Sorting of keys and values
d1={2:”Mumbai”,1:”Jaipur”,3:”Varanasi”}
print(d1)
sortedkeys=sorted(d1.keys())
sortedvalues=sorted(d1.values())
print(sortedkeys)
print(sortedvalues)

Output
{2: ‘Mumbai’, 1: ‘Jaipur’, 3: ‘Varanasi’}
[1, 2, 3]
[‘Jaipur’, ‘Mumbai’, ‘Varanasi’]

 

Tuples as keys and values.

d1={(1,2):(“One”,”Two”),(3,2):(“Three”,”Two”),(4,2):(“Four”,”Two”)}
print(d1)
print(d1[(1,2)])

Output
{(1, 2): (‘One’, ‘Two’), (3, 2): (‘Three’, ‘Two’), (4, 2): (‘Four’, ‘Two’)}
(‘One’, ‘Two’)

 

Leave a Reply