Class 11
Dictionaries..in…..Python…
For Computer Science students’
Hopefully, all of you go through the previous uploaded materials. In this material we discuss about “Dictionaries in
- Python”
DICTIONARIES in PYTHON
It is an unordered collection of items where each item consists of a key and a value.
It is mutable (can modify its contents) but Key must be unique and immutable.
Creating A Dictionary
It is enclosed in curly braces { } and each item is separated from other item by a
comma(,). Within each item, key and value are separated by a colon(:).
e.g.
d = {‘Subject':‘InformaticPractices','Class':‘11'}
(Note: Internally, dictionaries are arranged on the basis of keys. keys of a dictionary must
be of immutable types: a string, a number, a tuple……if you try to give a mututable type
as key, Python will give you an error as “unhashable type” )
Dictionaries are also called associative arrays or mappings or hashes.
Empty dictionary:-
d={} # it is an empty dictionary with no elements
OR
d = dict() # it is an empty dictionary created by using dict() constructor function
Accessing Elements of a Dictionary:-
d = {'Subject':'InformaticsPractices','Class':11}
print(d)
print("Subject:",d['Subject'])
print("Class:",d.get('Class'))
OUTPUT:-
{'Class':'11','Subject':'InformaticsPractices'}
('Subject:','InformaticsPractices')
('Class:',11)
Iterating Through A Dictionary
Following example will show how dictionary items can be accessed through loop.
e.g.
d = {'Subject':'InformaticsPractices','Class':11}
for i in d:
print(d[i])
OUTPUT:-
11
Informatics Practices
Accessing Keys or Values in A Dictionary
Following example will show you how you can access all the keys and values in a
dictionary.
keys() function returns all the keys defined in a dictionary
values() function returns all the values defined in a dictionary.
Example:
Output:-
Adding key:value pairs in a Dictionary
In this method, firstly an empty dictionary is created and then keys and values are added
to it one pair at a time.
Example:
Output:-
Specify key:value pairs in a Dictionary created using dict()
function:-
Example:-
Output:-
Specify comma separated key:value pairs in a Dictionary created
using dict() function:-
Example:-
Output:-
Specify keys separately and corresponding values separately in
a Dictionary created using dict() function:-
Example:-
Output:-
(Explanation: the keys and values are enclosed separately in parenthesis and are given
as arguments to the zip() function, which is then given as argument of dict() function. the
zip() is a pre - defined function which sets the first value ‘Ram’ in the first key ‘Name’ and
so on).
Specify key:value pairs separately in form of a squence in a
Dictionary created using dict() function:-
Example:-
Output:-
Adding elements to a dictionary:-
Example:-
Output:-
Nesting Dictionaries:-
Storing a dictionary inside another dictionary is called nesting of dictionaries.
Example:-
Output:-
(Explanation: a dictionary “Students” contains two students’ details “student1” and
“student2” which are also dictionaries.
So, for “Students” dictionary the two keys is “student1” and “student2”
In “student1” dictionary the three keys is “Name”, “Roll”, “Marks” and their corresponding
values is “arun”, “4”, and “65.3”
In “student2” dictionary the three keys is “Name”, “Roll”, “Marks” and their corresponding
values is “Uday”, “15”, and “78.2”
On the above example str() function is used to convert to string value from other type
value.)
Updating existing elements in a Dictionaries:-
we can change the value of an existing key using assignment operator(as dictionary is
mutuable)
Example:-
Output:-
Deleting elements from a Dictionaries:-
Two methods for deleting elements from a dictionary.
(1) using del command:-
del statement deletes element based on an existing key.
Example:-
Output:-
(2) using pop() method:-
The pop() method will not only delete the key:value pair for mentioned key but also it
returns the corresponding value.
Example:
Output:-
Deleting entire Dictionary:-
clear() method is used to clear entire dictionary.
Example:-
Output:-
Checking for existence of a key in a Dictionary:-
The in operator will return True if the given key is present in a dictionary, otherwise False.
The not in operator will return True if the given key is not present in a dictionary,
otherwise False.
Example:-
Output:-
Finding maximum / highest keys present in a dictionary:-
using max() function –
Example:-
Output:-
If you want to print the value of maximum / highest keys, then
Example:
Output:-
Finding minimum / lowest keys present in a dictionary:-
using min() function –
Example:-
Output:-
Display the keys or items of a dictionary in sorted order:- using
sorted() function
Example:-
Output:-
If you want to sort in descending order:
Example:-
Output:-
Built in Functions and Methods – works on dictionary:-
1) len() : - it returns the length of the dictionary.
Example:-
Output:-
2) clear() :- removes all elements from a dictionary
Example:-
Output:-
3) get() :- you can get the item with the given key.
Example:-
Output:-
4) items() :- returns all of the items in the dictionary
Example:-
Output:-
5) keys() :- returns all of the keys in the dictionary
Example:-
Output:-
6) values() :- returns all the values from the dictionary
Example:-
Output:-
7) update() :- merges the key:value pair from the new dictionary into the existing
dictionary.
Example:-
Output:
Note: if the key is same in the new dictionary then it overrides the value of the original
dictionary…………….
Look at the example:
Example:-
Output:-
8) copy() :- returns a copy of a dictionary
Example:-
Output:-
9) Pop() - method is used to return and delete the value of the key specified.
Example:-
Output:-
10) popitem() – it returns and removes an arbitrary element (key, value) pair from the
dictionary.
Example:-
Output:-
(Note: the above output may change in your computer as popitem() removes an
arbitrary element.)
11) fromkeys() - Sometimes there is a need to generate a dictionary from the given keys.
Function fromkeys() helps us achieve this very task with ease and using just a single
method.
Example:-
Output:-
12) setdefault() - it returns the value of a key (if the key is in dictionary). If not, it inserts
key with a value to the dictionary.
Example 1: when the key is in dictionary
Output:-
Example 2: when the key is not in the dictionary
Output:-
Topics may require during developing program on
dictionaries:
Printing a Dictionary in a different format:-
We generally use print() function for printing a dictionary.
Example:
then the output will be:-
the above code and displaying format is ok. but if the dictionary is large, then that format
is not readable and presentable.
For this, we need to import json module by giving the statement import json at the top of
our program and then use dumps() function of json module. (dumps() is a predefined
function of json module).
Example:-
Give 2 spaces in front of
every key: value pair
d is the
The output will be: dictionary
key : value pairs printed in separate
lines and 2 spaces in front of every
line as we set the indent = 2
split() function:-
the split() function breaks up a text based on white spaces. It mainly works on string type
data and breaks up a string into words and creates a list out of it.
Example:-
Look at the above code carefully:
t is a string type object
x is an object which holds the every words of t.
Now, x is what type object?
Yes, x is a list type object.
See below:
By default the split() function breaks up a string into words separated by white spaces but
In split() function you can also give a separator character.
Example:
Program Example: to count the frequency of a list elements using a dictionary
where the list elements are the keys and their frequencies are the corresponding
values.
Hints: Let a string x = “I am Ravi. I am nine years old”
Then the dictionary should be:
{ ‘I’: 2, ‘am’: 2, ‘Ravi.’:1, ‘nine’:1, ‘years’:1, ‘old’:1 }
Solution:
Output:
If we want to format the above output using json then the code will be:
Output:-
Program Example: Write a program to input n names and phone numbers to store it
in a dictionary and display the whole dictionary. (Where name is the key)
Solution:
Program Example: Write a program to input n names and phone numbers to store it
in a dictionary and display the whole dictionary (where name is the key). Then print
the phone number of a particular name given by the user.
Solution:
Program Example: Write a program to store n number of customers’ information
like customer id, customer name, customer address, customer phone no in a
dictionary based on customer id as key and display all information.
Hint: nested dictionary required here
Solution:
Program Example: Write a program to store n number of customers’ information
like customer id, customer name, customer address, customer phone no in a
dictionary based on customer id as key and display the particular record based on
customer id given by the user.
Hint: nested dictionary required here
Solution:
Program Example: Write a program to input names and price of n products and
store it in a dictionary and display the whole dictionary (where product name is the
key). Then print the total price of all products present on that dictionary.
Solution:
Tasks.
1. Create dictionary to store 4 student details with rollno, name, age field.
Search a particular student based on user given rollno.
2. Create dictionary for month and no of days for a year. User is asked to
enter month name and system will show no of days of that month.
3. Write a program to input n classes and names of their class teachers
to store it in a dictionary (where classes are the key) and display the
same. Also accept a particular class from the user and display the name
of the class teacher.
4. Write a program to input names of n students and their percentage of
marks in a dictionary (where name is the key), delete a particular name
from the dictionary and display the dictionary after deletion.
Read the whole materials carefully…..
Practice all solved programming examples.
Try to solve all programming tasks.
For any problem message or call me