Page 1
227
Chapter 3
Dictionaries
After studying this lesson, the students will be able to
? understand the need of dictionaries;
? solve problems by using dictionaries;
? get clear idea about dictionaries functions; and
? understand the difference between list and dictionary.
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': ' v al ue3' … ' ke yn': 'valuen'}
Note: Dictionary is created by using curly brackets(ie. {}).
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
{1: 'one', 2: 'two', 3: 'three'}
Page 2
227
Chapter 3
Dictionaries
After studying this lesson, the students will be able to
? understand the need of dictionaries;
? solve problems by using dictionaries;
? get clear idea about dictionaries functions; and
? understand the difference between list and dictionary.
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': ' v al ue3' … ' ke yn': 'valuen'}
Note: Dictionary is created by using curly brackets(ie. {}).
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
{1: 'one', 2: 'two', 3: 'three'}
228
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
A =
Map between keys and values
Example
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>> print computer
{'input': 'keyboard', 'os': 'windows-8', 'language': 'python', 'output': 'mouse'}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
{'wed': 'Wednesday', 'sun': 'Sunday', 'thu': 'Thursday', 'tue': 'Tuesday', 'mon':
'Monday', 'fri': 'Friday', 'sat': 'Saturday'}
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
1 one
2 two
3 three
Page 3
227
Chapter 3
Dictionaries
After studying this lesson, the students will be able to
? understand the need of dictionaries;
? solve problems by using dictionaries;
? get clear idea about dictionaries functions; and
? understand the difference between list and dictionary.
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': ' v al ue3' … ' ke yn': 'valuen'}
Note: Dictionary is created by using curly brackets(ie. {}).
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
{1: 'one', 2: 'two', 3: 'three'}
228
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
A =
Map between keys and values
Example
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>> print computer
{'input': 'keyboard', 'os': 'windows-8', 'language': 'python', 'output': 'mouse'}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
{'wed': 'Wednesday', 'sun': 'Sunday', 'thu': 'Thursday', 'tue': 'Tuesday', 'mon':
'Monday', 'fri': 'Friday', 'sat': 'Saturday'}
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
1 one
2 two
3 three
229
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
>>>
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be
done by using ‘for-loop’.
Example
Code
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print i,":", H[i]," ",
Output
>>>
Four: scanner one: keyboard three: printer two: Mouse
>>>
Page 4
227
Chapter 3
Dictionaries
After studying this lesson, the students will be able to
? understand the need of dictionaries;
? solve problems by using dictionaries;
? get clear idea about dictionaries functions; and
? understand the difference between list and dictionary.
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': ' v al ue3' … ' ke yn': 'valuen'}
Note: Dictionary is created by using curly brackets(ie. {}).
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
{1: 'one', 2: 'two', 3: 'three'}
228
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
A =
Map between keys and values
Example
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>> print computer
{'input': 'keyboard', 'os': 'windows-8', 'language': 'python', 'output': 'mouse'}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
{'wed': 'Wednesday', 'sun': 'Sunday', 'thu': 'Thursday', 'tue': 'Tuesday', 'mon':
'Monday', 'fri': 'Friday', 'sat': 'Saturday'}
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
1 one
2 two
3 three
229
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
>>>
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be
done by using ‘for-loop’.
Example
Code
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print i,":", H[i]," ",
Output
>>>
Four: scanner one: keyboard three: printer two: Mouse
>>>
230
OR
Code
H = {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
print "i value","\t","H[i] value"
for i in H:
print i,"\t", H[i]
Output
i value H[i] value
Four scanner
one keyboard
three printer
two Mouse
As said previously, the order of items in a dictionary is unpredictable.
Creating, initializing values during run time (Dynamic allocation)
We can create a dictionary during run time also by using dict () function. This way of
creation is called dynamic allocation. Because, during the run time, memory keys and
values are added to the dictionary.
Example
Write a program to input total number of sections and class teachers’ name in 11
th
class
and display all information on the output screen.
Code
classxi=dict()
n=input("Enter total number of section in xi class")
i=1
while i<=n:
a=raw_input("enter section")
Page 5
227
Chapter 3
Dictionaries
After studying this lesson, the students will be able to
? understand the need of dictionaries;
? solve problems by using dictionaries;
? get clear idea about dictionaries functions; and
? understand the difference between list and dictionary.
What is dictionary?
A dictionary is like a list, but more in general. In a list, index value is an integer, while
in a dictionary index value can be any other data type and are called keys. The key will
be used as a string as it is easy to recall. A dictionary is an extremely useful data storage
construct for storing and retrieving all key value pairs, where each element is accessed
(or indexed) by a unique key. However, dictionary keys are not in sequences and hence
maintain no left-to right order.
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called
keys) and a set of values. Each key maps a value. The association of a key and a value is
called a key-value pair.
Syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': ' v al ue3' … ' ke yn': 'valuen'}
Note: Dictionary is created by using curly brackets(ie. {}).
Example
>>> A={1:"one",2:"two",3:"three"}
>>> print A
{1: 'one', 2: 'two', 3: 'three'}
228
In the above example, we have created a list that maps from numbers to English words,
so the keys values are in numbers and values are in strings.
A =
Map between keys and values
Example
>>>computer={'input':'keybord','output':'mouse','language':'python','os':'windows-
8',}
>>> print computer
{'input': 'keyboard', 'os': 'windows-8', 'language': 'python', 'output': 'mouse'}
>>>
In the above example, we have created a list that maps from computer related things
with example, so here the keys and values are in strings. The order of the key-value
pairs is not in same order (ie. input and output orders are not same). We can get
different order of items in different computers. Thus, the order of items in a dictionary
is unpredictable.
Example
>>>
D={'sun':'Sunday','mon':'Monday','tue':'Tuesday','wed':'Wednesday','thu':'Thursda
y','fri':'Friday','sat':'Saturday'}
>>> print D
{'wed': 'Wednesday', 'sun': 'Sunday', 'thu': 'Thursday', 'tue': 'Tuesday', 'mon':
'Monday', 'fri': 'Friday', 'sat': 'Saturday'}
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
1 one
2 two
3 three
229
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
>>>
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be
done by using ‘for-loop’.
Example
Code
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print i,":", H[i]," ",
Output
>>>
Four: scanner one: keyboard three: printer two: Mouse
>>>
230
OR
Code
H = {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
print "i value","\t","H[i] value"
for i in H:
print i,"\t", H[i]
Output
i value H[i] value
Four scanner
one keyboard
three printer
two Mouse
As said previously, the order of items in a dictionary is unpredictable.
Creating, initializing values during run time (Dynamic allocation)
We can create a dictionary during run time also by using dict () function. This way of
creation is called dynamic allocation. Because, during the run time, memory keys and
values are added to the dictionary.
Example
Write a program to input total number of sections and class teachers’ name in 11
th
class
and display all information on the output screen.
Code
classxi=dict()
n=input("Enter total number of section in xi class")
i=1
while i<=n:
a=raw_input("enter section")
231
b=raw_input ("enter class teacher name")
classxi[a]=b
i=i+1
print "Class","\t","Section","\t","teacher name"
for i in classxi:
print "XI","\t",i,"\t",classxi[i]
Output
>>>
Enter total number of section in xi class3
enter sectionA
enter class teacher nameLeena
enter sectionB
enter class teacher nameMadhu
enter sectionC
enter class teacher nameSurpreeth
Class Section teacher name
XI A Leena
XI C Surpreeth
XI B Madhu
>>>
Appending values to the dictionary
We can add new elements to the existing dictionary, extend it with single pair of values
or join two dictionaries into one. If we want to add only one element to the dictionary,
then we should use the following method.
Syntax:
Dictionary name [key]=value
Read More