Dictionaries in Python Comp Sc
Dictionaries in Python Comp Sc
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” )
Empty dictionary:-
d={} # it is an empty dictionary with no elements
OR
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)
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
Following example will show you how you can access all the keys and values in a
dictionary.
Output:-
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:-
Example:-
Output:-
Specify comma separated key:value pairs in a Dictionary created
using dict() function:-
Example:-
Output:-
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).
Example:-
Output:-
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.)
Output:-
Output:-
Output:-
Output:-
Example:-
Output:-
Finding maximum / highest keys present in a dictionary:-
using max() function –
Example:-
Output:-
Output:-
Example:-
Output:-
Output:-
Output:-
Output:-
3) get() :- you can get the item with the given key.
Example:-
Output:-
Example:-
Output:-
Example:-
Output:-
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:-
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.
Output:-
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:
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:-
Example:-
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.
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 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.