Python Fundamentals – Dictionaries
INTRODUCTION
A dictionary is like an address-book where you can find the address or contact details of a person by knowing only his/her name, i.e., we associate keys (name) with values (details). Note that the key must be unique just like you cannot find out the correct information if you have two persons with the exact same name.
A dictionary is a very flexible object for storing various kind of information. A list is a collection of objects indexed by an integer going from 0 to the number of elements minus one. Instead of looking up an element through an integer index, it can be more handy to use a text. Roughly speaking, a list where the index can be a text is called a dictionary in Python. In other words, a dictionary is:
- An associative array.
- A mapping from keys to values.
- A container (collection) that holds key:value pairs.
CONCEPT OF KEY:VALUE PAIR
Python’s dictionary (its keyword is diet) is a data type that stores multiple data items (elements) of different types. A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps to a value. The association of a key and a value is called a keyrvalue pair or sometimes an item. Pairs of keys and values are specified in a dictionary by using the notation:
d = {key1 : value1, key2 : value2 }
Notice that the key rvalue pairs are separated by a colon and the pairs are separated themselves by commas and all this is enclosed in a pair of curly braces. For example, here is an empty dictionary and several dictionaries containing key:value pairs:
d1 = {} d2 = {'width': 8.5, 'height': 11} d3 = {1: 'RED', 2: 'GREEN', 3: 'BLUE', }
Note that a comma after the last pair is optional.
Python doesn’t store dictionary elements in any particular order. If you enter elements in one order, they may be stored in another (essentially random) order inside Python. The order of the key:value pairs is not the same. In fact, if you type the same example on your computer, you might get a different result. In general, the order of items in a dictionary is unpredictable. But that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values. For example,
››› info = {'Name': 'Mona', 'Age': 7, 'Class': 'First'}; ››› print info {'Name': 'Mona', 'Class': 'First','Age': 7 };
Characteristics of a Dictionary
- A dictionary is an unordered collection of objects.
- Values are accessed using a key.
- A dictionary can shrink or grow as needed.
- The contents of dictionaries can be modified.
- Dictionaries can be nested.
- Sequence operations, such as slice cannot be used with dictionaries.
CREATION, INITIALIZATION AND ACCESSING THE ELEMENTS IN A DICTIONARY
A collection that allows us to look up information associated with arbitrary keys is called a mapping. Python dictionaries are mappings. Some other programming languages provide similar structures called hashes or associative arrays. A dictionary can be created in Python by listing key:value pairs inside of curly braces. Here is a simple dictionary that stores some usernames and passwords.
››› passwd = {"Aman":"101", "Preeti":"204", " Babita":"107"}
Notice that keys and values are joined with a and commas are used to separate the pairs. The main use for a dictionary is to look up the value associated with a particular key. This is done through indexing notation. More than one entry per key not allowed, which means no duplicate key is allowed.
An empty dictionary (without any items) is written with just two curly braces, like this: {}.
››› dict1 = {} ››› dict1 {}
To add an item to the dictionary (empty string), we can use square brackets ([ ]) for accessing and initializing dictionary values. For example,
››› dict2 = {'name': 'Raj', 'deptcode': 7} ››› dict1, dict2 ({}, {'deptcode': 7, 'name': 'Raj'})
To access dictionary elements, you use the familiar square brackets along with the key to obtain its value:
››› dict2['name'] 'Raj' ›››
Dictionary dictl is empty while dict2 has two data items. The keys in dict2 are ‘name’ and ‘deptcode’, and their associated value items are ‘Raj’ and 7, respectively. Access to the value is through the key, as you can see from the explicit access to the ‘name’ key.
If we attempt to access a data item with a key which is not part of the dictionary, we get an error:
››› dict2['salary'] Traceback (innermost last): File "<stdin>", line 1, in ? KeyError: salary
In this example, we tried to access a value with the key ‘salary’ which, as you know, does not exist from the code above. The best way to check if a dictionary has a specific key is to use the dictionary’s has_key() method. The Boolean hasjkeyf) method will return a 1 if a dictionary has that key and 0 otherwise.
››› dict2.has_key('salary') 0 ››› dict2.haskey('name') 1 ››› dict2['name'] 'Raj '
Once the has_key() method has return 1, meaning that a key exists, then you can access it without having to worry about getting the KeyError.
Let us take a look at another dictionary example, using keys other than strings:
››› dict3 = {} ››› dict3[1] = 'abc' ››› dict3 ['1'] = 3.14159 ››› dict3[3.2] = 'xyz' ››› dict3 {3.2: 'xyz', 1: 'abc', '1': 3.14159}
Rather than adding each key:value pair individually, we could have also entered all the data for dict3 at the same time:
dict3 = { 3.2: 'xyz', 1: 'abc', '1': 3.14159 }
Creating the dictionary with a set key:value pair can be accomplished if all the data items are known in advance. The goal of the examples using dict3 is to illustrate the variety of keys that you can use.
Example 1
Program to enter name and percentage marks in a dictionary and then display informa¬tion on the screen.
# Program using dictionary to enter and display information on the screen rec=dict() num=input("Enter number of students :") i = 1 while i<=num: name=raw_input("Enter name of student :") per=raw_input ("Enter % marks of student :") rec[name]=per i = i +1 print "Name of Student","\t","% marks" for i in rec: print "\t",i,"\t\t",rec[i] RUN ››› Enter number of students :3 Enter name of student :Gagan Enter % marks of student :87% Enter name of student :Geeta Enter % marks of student :69% Enter name of student :Anita Enter % marks of student :95% Name of Student % marks Gagan 87% Geeta 69% Anita 95% ›››
Figure 17.1 Program for Example 1
Example 2
Program to enter name and percentage marks in a dictionary and then display informa¬tion in sorted order according to percentage marks.
# Program using dictionary to enter and display information in sorted order according to % marks rec=dict() num=input("Enter number of students :") i=1 while i<=num: name=raw_input("Enter name of student :") . per=raw_input ("Enter % marks of student :") rec[name]=per i = i + 1 ls = rec.keys() ls.sort() print "Name of Student","\t" , "% marks" for i in ls: print "\t",i,"\t\t",rec [i] RUN ››› Enter number of students : 4 Enter name of student : Uma Enter % marks of student : 56% Enter name of student :Tina Enter % marks of student : 84% Enter name of student : Sonu Enter % marks of student : 98% Enter name of student : Yash Enter % marks of student : 45% Name of Student % marks Sonu 98% Tina . 84% Uma 56% Yash 45% . ›››
Figure 17.2 Program for Example 2
How to Update Dictionaries?
You can update a dictionary by adding a new entry or element (i.e., a key:value pair), modifying an existing entry, or deleting an existing entry.
››› dict2['name'] = 'Raju' # update existing entry ››› dict2['deptcode'] = 5 # update existing entry ››› dict2['deptname'] = 'Sales' # add new entry
If the key does exist, then its previous value will be overridden by its new value. You may also add the contents of an entire dictionary to another dictionary by using the update() built-in method.
How to Remove Dictionary Elements and Dictionaries?
You can remove item from the existing dictionary by using del statement. You either remove individual dictionary elements or clear the entire contents of a dictionary. However, if you really want to “remove” an entire dictionary, use the del statement. Here are some deletion examples for dictionaries and dictionary elements:
del dictl['name'] # remove entry with key 'name' dictl.clear() # remove all entries in dictl del dictl # delete entire dictionary
DICTIONARY FUNCTIONS AND METHODS
Just like the other built-in types, dictionaries have methods and functions.
dict()
The dict() constructor builds dictionaries directly from lists of key:value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key:value list.
››› dict([('Amit', 4139), ('Ramesh', 4127), ('John', 4098)]) {'Amit': 4139, 'John': 4098, 'Ramesh': 4127}
Because dict() is the name of a built-in function, you should avoid using it as a variable name. You can create a dictionary during run time using dict(), also called dynamic allocation.
cmp()
This is used to check whether the given dictionaries are same or not. If both are same, it will return 0, otherwise return 1 or -1. If the first dictionary having more number of items, then it will return 1, otherwise return -1.
››› D1 = {'Sun': 1, 'Mon': 2, 'Tue': 'Fri': 6, 'Sat': 7 } 3, 'Wed' : 4, 'Thurs': 5, ››› D2 = {'Sun': 1, 'Mon': 2, 'Tue': 'Fri': 6, 'Sat': 7 } 3, 'Wed' : 4, 'Thurs': 5, ››› D3 = {'Sun': 1, 'Mon': 2, 'Tue': 3, 'Wed': 4, 'Thurs': 5 } ››› cmp(Dl,D3) #both are not equal 1 ››› cmp(D1,D2) #both are equal 0 ››› cmp(D3,D1) -1
len()
The len() built-in function gives us the number of items in a dictionary, i.e., it returns the number of key:value pairs:
››› temps = {'Delhi': 20.2, 'Allahabad': 15.4, 'Goa': 10.5} ››› len(temps) 3
clear()
The clear() method removes all items from the dictionary.
››› d = {} ››› dt'name'] = 'Vivek' ››› d['age'] = 18 ››› d {'age': 18, 'name': 'Vivek'} ››› returnedvalue = d.clear() ››› d {} >>> print returned_value None
get()
The get() method is an easy way to get a value from a dictionary. Ordinarily, when you try to access an item that is not present in the dictionary, things go very wrong:
››› d = {} ››› print dt'name'] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: 'name'
But when you use get() function it displays None:
››› print d.get('name') None
As you can see, when you use get to access a non-existent key, there is no exception. Instead, you get the value None. You may supply your own “default” value, which is then used instead of None:
››› d.get('name', 'N/A') 'N/A'
has_key()
The has_key() method checks whether a dictionary has a given key. The expression d.has_key(k) is equivalent to k in d.
››› d = {} ››› d.has_key('name') False ››› dt'name'] = 'Mohan' ››› d.has_key('name') True
pop()
The pop() method can be used to get the value corresponding to a given key, and then remove the key:value pair from the dictionary:
››› d = {'x': 1, 'y': 2} ››› d.pop('x') 1 ››› d {'y': 2}
popitem()
The popitem() method is similar to list.pop, which pops off the last element of a list. Unlike list.pop, however, popitem pops off an arbitrary item because dictionaries don’t have a “last element” or any order whatsoever. This may be very useful if you want to remove and process the items one-by-one in an efficient way (without retrieving a list of the keys first):
››› d {'publisher': 'BPB', 'price': 99, 'title': 'Computer Science'} ››› d.popitem() ('publisher', 'BPB') ››› d {'price': 99, 'title': 'Computer Science'}
Although popitem is similar to the list method pop, there is no dictionary equivalent of append (which adds an element to the end of a list). Because dictionaries have no order, such a method wouldn’t make any sense.
keys()
The keys and values can be extracted as lists from a dictionary. The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order.
››› temps = {'Delhi': 20.2, 'Allahabad': 15.4, 'Goa': 10.5} ››› temps.keysO ['Delhi', 'Allahabad', 'Goa']
values()
The values() method returns list of values.
››› temps = {'Delhi': 20.2, 'Allahabad': 15.4, 'Goa': 10.5} ››› temps.values() [20.2, 15.4, 10.5]
items()
Returns a list of tuples (key,value) representing the key:value pairs. These are useful for when you wish to iterate through a dictionary’s keys or values, even though in no par¬ticular order.
››› temps = {'Delhi': 20.2, 'Allahabad': 15.4, 'Goa': 10.5} ››› temps.item() [('Delhi': 20.2), ('Allahabad': 15.4), ('Goa': 10.5)]
Example 3
Program that converts dictionary to list.
# Convert dictionary to list of tuples. vegetables = {"carrot" : 1, "peas" : 2, "onion" : 4} items = list(vegetables.items()) for item in items: print(len(item), item) RUN ››› 2 ('carrot' , 1) 2 ('peas', 2) 2 ('onion', 4) ›››
Figure 17.3 Program for Example 3
SOLVED EXERCISE
Question 1.
What is dictionary?
Answer:
A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables.
Question 2.
Compare and contrast dictionaries (diets) with other Python data types.
Answer:
(a) Dictionaries are a container type that stores data, like lists and tuples.
(b) Dictionaries are a mapping data type indexed by keys.
(c) A dictionary’s elements (the items it contains) are key:value pairs. In contrast, lists and tuples store data by using numeric indexes (they are sequence data types) and support indexing and slicing.
(d) Dictionaries are mutable. That means a dictionary can be modified in place you don’t have to create a copy of it to modify it (as you do with strings and tuples). However, a diet’s keys must be immutable.
Question 3.
What are the advantages of hash?
Answer:
Hashes are used for space-efficient storage, for security and cryptography, and so on. Another benefit of hashing is that after the hash is computed, keys can be looked up directly, there’s no need for the computer to search through a whole list of keys. In Python, this feature makes dictionaries very fast.
Question 4.
Can Python store dictionary elements in any particular order?
Answer:
Python doesn’t store dictionary elements in any particular order. If you enter elements in one order, they may be stored in another (essentially random) order inside Python. For example,
››› D1 = {'sleep': "All night", 'work': "All day"} ››› D1 {'work': 'All day', 'sleep': 'All night'}
Question 5.
What is a mapping?
Answer:
A mapping is a structure in which values are stored and retrieved according to a key. This is often called a dictionary, because it behaves similarly to a common dictionary.
Question 6.
What is the another name for a mapping?
Answer:
A dictionary.
Question 7.
What are the characteristics of a Python dictionary?
Answer:
Characteristics of a Python dictionary are as follows:
(a) A dictionary is an unordered collection of objects.
(b) Values are accessed using a key rather than by using an ordinal numeric index.
(c) A dictionary can shrink or grow as needed.
(d) Dictionaries can be nested.
(e) The contents of dictionaries can be modified.
Question 8.
A dictionary is an mutable object. Comment.
Answer:
A dictionary is mutable because its existing items can be modified, new items can be added, and existing items can be deleted.
Question 9.
A dictionary is an unordered collection of objects. Comment.
Answer:
The items in a dictionary are not maintained in any specific order, and a dictionary can contain references to any type of objects.
Question 10.
Can sequence operations, such as slicing and concatenation be applied to dictionaries?
Answer:
No, a dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.
Question 11.
Write the syntax of a dictionary.
Answer:
A dictionary consists of none, one, or more key lvalue pairs, separated by commas, and enclosed in a pair of curly braces.
Question 12.
Can you remove keyivalue pairs from a dictionary, and if so, how?
Answer:
You can use del to remove an existing keyivalue pair from a dictionary.
Question 13.
What do you mean by traversing a dictionary?
Answer:
Traversing a dictionary means visit each element of the dictionary to display its values on the screen.
Question 14.
Can you merge two dictionaries?
Answer:
Two dictionaries can be merged in to one by using update () method. It merges the keys and values of one dictionary into another and overwrites values of the same key.
Question 15.
Write a program to traverse a dictionary and display its value on the screen in different lines.
Answer:
DAYS = { 'Sunday': 1, 'Monday': 2, 'Tuesday': 3, 'Wednesday': 4, 'Thursday': 5, 'Friday': 6, 'Saturday': 7, } for i in DAYS: print i," DAYS[i] RUN ››› Monday : 2 Tuesday : 3 Friday : 6 Wednesday : 4 Thursday : 5 Sunday : 1 Saturday : 7 ›››
Figure 1 Program for Q15
Question 16.
Write a program to traverse a dictionary and display its value on the screen in same line.
Answer:
DAYS = { 'Sunday': 1, 'Monday': 2, 'Tuesday': 3, 'Wednesday': 4, 'Thursday': 5, 'Friday': 6, 'Saturday': 7, } for i in DAYS: print i,":", DAYS[i], RUN ››› Monday : 2 Tuesday : 3 Friday : 6 Wednesday : 4 Thursday : 5 Sunday : 1 Saturday : 7 ›››
Figure 2 Program for Q16
Question 17.
Write a program to create dictionary and display information on the screen.
Answer:
# Program to create dictionary and display information on the screen compscience=dict() num= input("Enter number of students opted for Python Language :") i = 1 while i<=num: name=raw_input("Enter name of student :") grade=raw_input ("Enter grade of student :") compscience[name] =grade i=i+1 print "Computer Science","\t","Name of Student","\t","Grade" for i in compscience: print "Python","\t\t\t",i,"\t\t",compscience[i] RUN ››› Enter number of students opted for Python Language : 2 Enter name of student : Vivek Enter grade of student : A1 Enter name of student : Abhishek Enter grade of student : A2 Computer Science Name of Student Grade Python Abhishek A2 Python Vivek A1 ›››
Figure 3 Program for Q17
Question 18.
Write a program to put information on the screen in ascending order of names.
Answer:
# Program to information on the screen in ascending order of names compscience=dict() num=input("Enter number of students opted for Python Language: " i = 1 while i<=num: name=raw_input("Enter name of student :") grade=raw_input (" Enter grade of student :") compscience[name] = grade i=i+1 ls = compscience.keys() ls.sort () print "Computer Science","\t","Name of Student","\t","Grade" for i in ls: print "Python","\t\t\t",i,"\t\t" ,compscience[i] ››› Enter number of students opted for Python Language : 3 Enter name of student : Seema Enter grade of student : B2 Enter name of student : Vivek Enter grade of student : A1 Enter name of student : Abhishek Enter grade of student : A2 Computer Science Name of Student Grade Python Abhishek A2 Python Seema B2 Python Vivek A1 ›››
Figure 4 Program for Q18
Question 19.
Explain cmp() function of Python.
Answer:
Python built-in function cmp() accepts two values as parameters and returns -1, 0 or 1, corresponding to the relative ordering of the parameters. Thus, cmp(a,b) returns -1 if a precedes b, 0 if they are the same, and 1 if a follows b.
Question 20.
What does the keys(), valuesQ and items() function do?
Answer:
keys(): Returns a list of the keys.
values(): Returns a list of the values.
items(): Returns a list of tuples (key,value) representing the key:value pairs.
Question 21.
Write a program to create students details and then delete particular roll no using name.
Answer:
# Program to create students details and then delete particular roll no using name details=dict() num= input("Enter number of students whose information you want to enter :") i=1 while i<=num: name=raw_input("Enter name of the student :") rno=raw_input ("Enter roll number of the student :") details[name]=rno i=i + 1 name= raw_input("Enter name of student you want to delete :") del details[name] ls=details.keys() print " Student information after deleting" print "Name of Student","\t","Rno" for i in ls: print "\t",i,"\t\t",details[i] RUN ››› Enter number of students whose information you want to enter : 3 Enter name of the student :Rahul Enter roll number of the student :6 Enter name of the student :Suman Enter roll number of the student :9 Enter name of the student :Tina Enter roll number of the student :15 Enter name of student you want to delete :Suman Student information after deleting Name of Student Rno Tina 15 Rahul 6 ›››
Figure 5 Program for Q21
Question 22.
Write different capabilities of dictionary.
Answer:
A dictionary has the following capabilities:
(a) Ability to iterate over keys or values or keyvalue pairs.
(b) Ability to add keyvalue pairs dynamically.
(c) Ability to lookup a value by key.
Question 23.
Find the output of the following programs:
(a) ››› dict2 = { 'name': 'Ajay', 'rno': 8 } ››› len(dict2) (b) ››› d = {'publisher': 'BPB', 'price': 99, 'title': 'Computer Science'} ››› d.keys() (c) ››› d = {'publisher': 'BPB', 'price': 99, 'title': 'Computer Science'} ››› d.values() (d) ››› d = {'publisher': 'BPB', 'price': 99, 'title': 'Computer Science'} ››› d.item() (e) ››› dictl = {} ››› dict1 (f) ››› cmp(1, 2) ››› cmp("a","b") ››› cmp(3, 1) ››› cmp(3.1, 3.1)
Answer:
(a) 2
(b) [‘publisher’, ‘price’, ‘title’]
(c) [‘BPB’, ’99’, ‘Computer Science’]
(d) [(‘publisher’: ‘BPB’), (‘price’: 99), (title’: ‘Computer Science’)]
(e) {}
(f) -1
-1
1
0
Multiple choice questions
Question 1.
The association of a key and a value is called:
(a) A key-value pair
(b) An item
(c) Both (a) and (b)
(d) All of the above
Answer:
(c)
Question 2.
Dictionary are represented using:
(a) {}
(b) []
(c) ()
(d) None of the above
Answer:
(a)
Question 3.
In general, the order of items in a dictionary is:
(a) Unpredictable
(b) Predictable
(c) known
(d) None of these
Answer:
(a)
Question 4.
If the dictionary lengths are different, then for cmp(dict1, dict2), cmp() will return___number if dictl is longer:
(a) Positive number
(b) Negative number
(c) Zero
(d) All of the above
Answer:
(a)
Question 5.
The dictionaries have the same length, same keys, and same values for each key, then the dictionaries are an exact match and returns:
(a) 1
(b) -1
(c) 0
(d) None of these
Answer:
(c)