0% found this document useful (0 votes)
34 views63 pages

Dictionaries

A dictionary in Python is an unordered, mutable collection of key:value pairs, defined using curly brackets. Keys must be unique and of immutable types, while values can be of any type. The document explains various operations on dictionaries, including creation, accessing elements, updating, merging, and removing items, along with examples and characteristics of dictionaries.

Uploaded by

Charvi Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views63 pages

Dictionaries

A dictionary in Python is an unordered, mutable collection of key:value pairs, defined using curly brackets. Keys must be unique and of immutable types, while values can be of any type. The document explains various operations on dictionaries, including creation, accessing elements, updating, merging, and removing items, along with examples and characteristics of dictionaries.

Uploaded by

Charvi Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Dictionaries

A dictionary is a collection which is unordered,


mutable and do not allow duplicates.
Dictionaries are used to store data values in
key:value pairs.
Dictionaries are written with curly brackets,
Dictionaries and have keys and values:
Example:
D={“vowel1”:”a”, “vowel2”:”e”, “vowel3”:”i”,
“vowel4”:”o”, “vowel5”:”u”}
>>>Month={“January":31,"February":28,"March":31,"
April":30,"May
":31,"June":30,"July":31,"August":31,"September":30,
"October":31," November":30, "December":31}
Notice that:
Creating and 1. Curly braces mark the beginning and end of the
Accessing dictionary
2. Each entry (key:value) consists of a pair separated
Dictionaries by a colon. The key and corresponding value is given
by writing colon(:) between them. 3. The key:value
pairs are separated by comma.
Internally dictionaries are indexed (i.e.) arranged on
the basis of keys.
Some more dictionary declaration
Emptydictionary={ }
subjectandcode={"Physics":42,"Chemistry":43, "Mathematics":41,
"Biology":44,"Computer Science":83,"English":75}
Note:
Dictionaries are also called Associative Arrays or mappings or hashes.
Keys of a dictionaries must be of immutable type such as Python
string, Number, a tuple (containing only immutable entry) but list which
is mutable can not be used as keys of a dictionary.
>>>dict2={[2,3]:”abc”} #TypeError: Un-sharable Type ‘list’
Its general syntax is dictionaryname <key>
>>> subjectandcode[”Biiology"]
44
Accessing >>> subjectandcode["Computer Science"]
elements of a 83
dictionary A dictionary operation that takes a key and
finds the corresponding value is called
lookup
Accessing entire dictionary
>>>dictionaryname
• Mentioning only the dictionary name without any key prints the entire dictionary.
• If the key in square bracket is used along with dictionaryname produces the value
that matches the key otherwise error is displayed. Example:
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer Science':
83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 2}
>>> subjectandcode["Hindi"]
2
Access Dictionary Keys:Value one by one
through Loop
>>> for subject in subjectandcode:
print(subject,":",subjectandcode[subject])
Physics : 42
Chemistry : 43
Mathematics : 41
Biology : 44
Computer Science : 83
English : 75
Write a program to read roll numbers and marks of four students and create
a dictionary from it having roll number as keys.
rno=[]
mks=[]
for a in range(4):
r,m=eval(input("enter roll no, marks:"))
rno.append(r)
mks.append(m)
d={rno[0]:mks[0],rno[1]:mks[1],rno[2]:mks[2],rno[3]:mks[3]}
print("dictionary : ",d)
Output
enter roll no, marks:1,67
enter roll no, marks:2,45
enter roll no, marks:3,50
enter roll no, marks:4,60
dictionary : {1: 67, 2: 45, 3: 50, 4: 60}
Accessing Keys and Values
keys() is used to see all the keys in a dictionary.
>>> subjectandcode.keys()
dict_keys(['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer
Science', 'Informatics Practices', 'English', 'Hindi’])
values() is used to see all the values in a dictionary
>>> subjectandcode.values()
dict_values([42, 43, 41, 44, 83, 65, 101, 2])
List() - convert dictionary into list.
>>> list(subjectandcode.keys())
['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer Science',
'Informatics Practices', 'English', 'Hindi']
Accessing Keys and Values
The keys of Dictionaries converted into list can be stored in a list
variable.
>>> Subject=list(subjectandcode.keys())
>>>Subject ['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer
Science', 'Informatics Practices', 'English', 'Hindi’]
>>> SubjectCode=list(subjectandcode.values())
>>>SubjectCode [42, 43, 41, 44, 83, 65, 101, 2]
Question
Given a dictionary M which stores the
marks of the students of class with roll
numbers as the keys and marks as
values. Write a program to check if
anyone has scored marks as 90.
if 90 in d.values():
print("found")
else:
print("not found")
Characteristics of Dictionary
Dictionary is mutable like list. Except this there is no similarity with list. It has following
attributes:
1. Unordered set: Dictionary is an unordered set of keys:value pairs. Its value can contain
references to any type of object.
2. Not a sequence: Unlike string,, lists and tuples a dictionary is not a sequence because
it is unordered. The sequence are indexed by a range or ordinal numbers. Hence they
are ordered but dictionaries are unordered collection.
3. Indexed by Keys and not Numbers: Dictionaries are indexed by keys. According to
Python, a key can be ”any non-mutable type”. Since Strings and Numbers are non
mutable it can be used as keys. Tuple if containing immutable objects (integers and
strings), can be used as keys. A value in a dictionary can be of any type and type can be
mixed within one dictionary.
Characteristics of dictionary
4. Keys must be unique: Each of the keys within a dictionary must be unique. Since keys are
used to identify values in a dictionary, there can not be duplicate keys in a dictionary.
However two unique keys have same value.
5. Mutable: Like list, dictionaries are also mutable. We can change the value of a certain
key “in place” using the assignment statement as per following syntax
>>> subjectandcode["Hindi"]
2
>>> subjectandcode["Hindi"]=102
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer Science': 83,
'Informatics Practices': 65, 'English': 101, 'Hindi': 102}
Characteristics of Dictionary
6. We can add new key:value pair to existing dictionary:Using following
syntax a new Key:value pair can be added to dictionary.
dictionary[“new”]=“a new pair is added”
>>> subjectandcode["Sanskrit"]=122
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44,
'Computer Science': 83, 'Informatics Practices': 65, 'English': 101,
'Hindi': 102, 'Sanskrit’:122}
Characteristics of Dictionary
7. Internally Dictionary is stored as mapping: Internally the key:value
pairs of a dictionary are associated with one another with some
internal function(called hash-function-algorithm to map and link a key
with a stored value). This way of linking is called mapping.
WORKING WITH DICTIONARY
1. Multiple ways of creating Dictionary: Various ways are as below:
(a) Initializing a Dictionary: In this method all the Keys:values pairs of a dictionary
are written collectively, separated by commas and enclosed in curly braces.
Employee={“Name”:”Bimlendu Kumar”, ”Department”: ”Computer Science”,
”Joining Year”:2007}
(b) Adding Key:value pairs to an Empty Dictionary : In this method first we create a
empty dictionary and then keys and values are added to it.
>>> emp=dict() #or emp={ }
>>> emp
{}
>>> emp["Computer Science"]=”Python”
>>> emp
{'Computer Science': ‘Python'}
(c) Creating a dictionary from name and values pairs: Using dict() constructor we can create
dictionary from any key :value pair.
>>> Emp1=dict(name="Prakash",Subject="Computer",School=”KV Delhi")
>>> Emp1
{'name': 'Prakash', 'Subject': 'Computer', 'School': ‘KV Delhi’}
or specify comma separated key:value pairs
>>> Emp2=dict({"name":"Rishi","Subject":"Informatics Practices","School":”DAV Delhi"})
>>> Emp2
{'name': 'Rishi', 'Subject': 'Informatics Practices', 'School': ‘DAV Delhi’}
(d) Specify Keys Separately and corresponding values separately:
>>> EMP4=dict(zip(("name","Subject","School"),("Raman",”CS",”DAV")))
>>> EMP4
{'name': ‘Raman', 'Subject': ‘CS', 'School': ‘DAV’}
zip() function clubs first key with first value, second key with second value and so on
(e) Specify Keys:value pairs Separately in the form of sequence : Using List
>>> Emp=dict([ ["name","Jay"], ["Subject","Computer Science"],
["School","KV "]])
>>> Emp
{'name': 'Jay', 'Subject': 'Computer Science', 'School': 'KV’}
Using Tuples
>>> Emp1=dict((("name","Suman"),("Subject","Computer
Science"),("School","KV ")))
>>> Emp1
{'name': ‘Suman', 'Subject': 'Computer Science', 'School': 'KV’}
Note: Using dict() method to create a dictionary takes longer time compared
to traditional method of enclosing values in { }. Thus it should be avoided
until it becomes necessity.
Adding elements to dictionary
We can add new elements (key:value) to a dictionary using assignment
as per syntax given below:
<dictionary>[<key>]=<value>

>>> Subject={"Computer":"083","Informatics Practices":"065"}


>>> Subject {'Computer': '083', 'Informatics Practices': '065’}
>>> Subject["English"]="101"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
Updating elements of dictionary
We can update value of an existing element (kye:value) to a dictionary using
assignment as per syntax given below:
[]=
>>> Subject {'Computer': '083', 'Informatics Practices': '065', 'English': '101’}
>>> Subject["English"]="001"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001’,}
Note: To add and to update the syntax is exactly same but in case adding the
Key must be a new unique key and for updating the key must be an existing
key and the value will be a new value by which the key value have to be
changed.
Merging dictionaries: An update ( )
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.
Example
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
Removing an item from dictionary
We can remove item from the existing dictionary by using del key word.
Syntax: del dicname[key]
Example
x = {“name” : "Aman", “age” : 37, “country” : "India”}
del x['age’]
print(x)
OUTPUT->{'country': 'India', 'name': 'Aman’}
del x -> will remove complete dictionary
(b) pop() - Removes and returns the dictionary element associated to the passed key.
>>> Subject.pop("Computer")
'083‘ # popped key value is returned by pop() function which is displayed
>>> Subject
{'Informatics Practices': '065', 'English': '001’}
d={'a':10,'b':2}
l=d.pop('d',-1)
print(l)
-1
Checking for presence / absence of a key in Dictionary
Usual Membership operator in and not in work with dictionary as well to check for
the presence / absence of a key in the dictionary.
>>> emp={'age':25,"Salary":10000,"name":"sanjay"}
>>> "age“ in emp
True
>>> "name" in emp
True
>>> "basic" in emp
False
>>> "basic" not in emp
True
Note: in and not in operator check for membership only in keys not in values.
Exercise:
Write a program :
1. to create a dictionary containing names of competition winner
students as keys and number of their wins as values.
2. to input a key and delete it from the dictionary. Display error
message if the roll number does not exist in dictionary.
3. to check a value exists in the dictionary and display its key
otherwise display ‘value not found’.
Ans 3
dict1={0:"Zero",1:"One",2:"Two",3:"Three",4:"Four",5:"Five"}
ans='y’
while ans=='y' or ans=='Y’:
val=input("Enter Value: ")
print("Value ",val, end=" ")
for k in dict1:
if dict1[k] == val:
print("Exists at ",k)
break;
else:
print("Not Found")
ans=input("Want to check another value:(y/n)? :- ")
DICTIONARY FUNCTIONS
AND METHODS
Q1. The dictionary S stores the roll_no:names
of the students who have been selected to
participate in national event. Write a program
Practice to display the roll numbers selected.
questions Q2. The dictionary S stores the roll_no:names
of the students who have been selected to
participate in national event. Write a program
to display the names of selected students.
Practice questions
Q3 Write a menu driven program to input your friends names, their
Phone Numbers and store them in the dictionary as key-value pair.
Perform the following operations on the dictionary:
a. Display the name and phone number of all your friends.
b. Add a new key-value pair and display the modified dictionary.
c. Delete a particular friend from the dictionary.
d. Modify the phone number of existing friend.
e. Check if a friend is present in the dictionary or not
f. Display the dictionary in sorted order of names.
Counting frequency of elements in a list using
dictionary
Here we can use split() function, which works on string type data, to
break up a string into words and create a list.
string=“this is a string”
words=string.split()
words
[‘this’, ’is’, ’a’, ‘string’]
string='this is a a string' d={}
words=string.split()
string="this is my program"
print(words) for i in string:
d={} a=string.count(i)
d[i]=a
for key in words: print(d)
if key not in d:
count=words.count(key)
d[key]=count
print(d)
Output -
['this', 'is', 'a', 'a', 'string']
{'this': 1, 'is': 1, 'a': 2, 'string': 1}
Creation dictionary from keys- fromkeys() method
fromkeys() – is used to create dictionary from keys and a common value will
be assigned to all the keys.
Syntax – dict.fromkeys(<key sequence>,[<value>])
keys = {'a', 'e', 'i’ , 'o', 'u’ }
value =”vowel"
vowels = dict.fromkeys(keys, value)
print(vowels)
OUTPUT-> {'i': 'Vowel', 'u': 'Vowel', 'e': 'Vowel', 'a': 'Vowel', 'o': 'Vowel’}
nd=dict.fromkeys([2,4,6,8],100) #key sequence given in list form
OUTPUT-> {2: 100,4: 100, 6: 100,8: 100}
Note: Keys and argument must be an iterable
sequence, even if you have a single key
Example both of the following statements will
give error:
K=dict.fromkeys(5)
fromkeys() K=dict,fromkeys(5,)
method
Correct way:
K=dict.fromkeys((5,))
K=dict.fromkeys([5])
Single iterable element should be given in
tuple or list form.
fromkeys() method

k= dict.fromkeys((1,2,3),(4,5,6))
Output:
{1: (4, 5, 6), 2: (4, 5, 6), 3: (4, 5, 6)}

K=dict.fromkeys((1,2,3))
Output
{1: None, 2: None, 3: None}
Practice Question
Q1. An Institute has decided to
deposit scholarship amount of
Rs.2000/- to some students. Write a
program to input the selected
students’ roll no and create a
dictionary for the same.

Output :
{10:2000,25:2000,30:2000}
setdefault() method
It inserts a new key:value pair ONLY IF the key doesn’t already exist.
If the key exist, it returns the current value of the key. The existing
value of the key will not be updated
dict.setdefault(<key>,<value>)
Marks={1:30,2:40,3:50}
Marks.setdefault(4,20)
{1:30,2:40,3:50,4:20} #new key:value added
Marks.setdefault(2,50)
{1:30,2:40,3:50,4:20} #no change
popitem()
This method removes and returns the last key:value pair from
the dictionary.
It follows the LIFO (Last IN First Out) structure.
This method accepts no parameter.
Syntax - <dict>.popitem()
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d.popitem()
Here it will return (4,’Mohan’) as output.
If the dictionary is empty, calling popitem() raises a KeyError
Exercise
Write a program to delete the keys of a dictionary, one by one in LIFO
order. Make sure that there is no error generated after the last item
delete.
Sorted()
This method is used to sort the specified keys or
values. It will accept two parameters: One is the
dictionary object and second is the reverse.
The default value of reverse is False.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d))
The above code will return the list of keys as :
[2, 4, 11, 30]
If you want to sort keys in descending order
use reverse=True.

Observe this:
Sorted() d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(sorted(d, reverse=True))

The above code output is: [30, 11, 4, 2]


If you want to sort the values it will
be used in this manner.
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Moha
n"}
print(sorted(d.values(), reverse=True))
['Vatsal', 'Vansh', 'Mohan', 'Jahan’]
Sorted()
Similarly, you can use the items()
method to sort key-value pairs and
the answer will be returned in the
form of tuples with key-value pairs
sorted by keys.
sorted()

For sorted() function to work, all the keys should be homogeneous


(same data type and on which comparison are possible otherwise
python will raise an error)

Sorted() function will return the sorted result always in list form.
It will return the maximum key or
value as specified in the code.
Observe this example:

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Moha
max() n"}
print(max(d))
print(max(d.values()))
The second line returns 30 and the
third line returns ‘Vatsal’.
min()
It will return the minimum key or value as
specified in the code. Observe this
example.

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}
print(min(d))
print(min(d.values()))
It will make the sum of all the
specified keys or values.
Example:
d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Moha
Sum() n"}
print(sum(d))

47
copy()
It is used to create a shallow copy of a dictionary.
Shallow copy refers to copying upper layers rather than inner objects.
The example is as follows:

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d1=d.copy()

It will copy the dictionary one to another.


We can use the assignment operator to copy the dictionaries.
d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}
d1=d
copy()
If the values referenced by the key are immutable, then any changes
made in the copy created with copy() will not be reflected in the
original dictionary as the copy dictionary has its own set of referencing
keys.
If the values referenced by the key are mutable, then the keys will be
referring to the same Python list objects(same memory address) but
lists being mutable values can change
Copy()
Copy()
Nesting Dictionaries

Storing a dictionary inside another dictionary is called nested


dictionaries. A dictionary can store dictionary as value only, inside it.
Example:Create a dictionary with names of 2 employees, with their
age,salary and access them.
employees =
{'Aman’:{‘age’:25,'salary':10000},'Mayur’:{‘age’:35,'salary':51000}}
employee1 = employees['Aman’]
print(employee1)

OUTPUT {‘age’:25, 'salary': 10000}


Questions.
1. Create dictionary to store 4 student details with rollno,name,age
field. Search student in list.
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.
Ans 1.
students
={'st1':{'rno':1,'name':'Aman','age':12},'st2':{'rno':11,'name':'Sapna','age':14}}
student1 = students['st1']
print(student1)

Output
{'rno': 1, 'name': 'Aman', 'age': 12}
Q1. Write a Python script to generate and print a dictionary that
contains a number (between 1 and n) in the form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Q2. Write a Python program to sum all the items in a dictionary.
Ans1.
n=int(input("Input a number "))
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Ans2.
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
Consider the following dictionary stateCapital:
stateCapital={"AndraPradesh":"Hyderabad","Bihar":"Patna","Maharashtra":"
Mumbai","Rajasthan":"Jaipur"}
Find the output of following statements:
print(stateCapital.get('Bihar'))
print(stateCapital.keys())
print(stateCapital.values())
print(stateCapital.items())
print(len(stateCapital))
print("Maharashtra" in stateCapital)
print(stateCapital.get("Assam"))
del stateCapital["AndraPradesh"]
print(stateCapital)
Output -
Patna
dict_keys(['AndraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
dict_items([('AndraPradesh', 'Hyderabad'), ('Bihar', 'Patna'), ('Maharashtra',
'Mumbai'), ('Rajasthan', 'Jaipur')])
4
True
None
{'Bihar': 'Patna', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur'}
Q1. Given the dictionary d={‘k1’:’v1’, ‘k2’:’v2’, ‘k3’:’v3’}, Create a dictionary
with opposite mapping i.e. write a program to create the dictionary as :
Inv_d={’v1’:’k1’, ’v2’: ’k2’, ‘v3’:’k3’}

Q2. Write a program that checks if two same value in a dictionary have
different keys. That is, for dictionary
D1={ ‘a’:10, ‘b’:20, ‘c’:10}
The program should print “2 keys have same values” and for
D2={‘a’:10, ‘b’:20, ’c’:30}
The program should print “No keys have same values”
Ans1.
d={'k1':'v','k2':'v2','k3':'v3'}
inv_d = {}
for k, v in d.items():
inv_d[v] = inv_d.get(v,[]) + [k]
print(inv_d)

{'v': ['k1'], 'v2': ['k2'], 'v3': ['k3']}

You might also like