DICTIONARIES
What is Dictionary?
A Dictionary is an unordered collection of elements in the form of key and value pair. All
elements are kept within Curley bracket. Dictionary is mutable.
Example-1
D={10:’Rahul’,20:’Deepak’,30:’Swagat’}
1,2,3 are keys
Rahul, Deepak and Swagat are values
Example-2
D={“January”:31, “February”:28,”March”:31}
IMPORTANT NOTE:
Keys can’t be repeated but values can be.
HOW CAN YOU CREATE AN EMPTY DICTIONARY?
D={ }
HOW CAN YOU ACCESS AN ELEMENT OF A DICTIONARY?
D={1:’Rahul’,2:’Deepak’,3:’Swagat’}
print(D[1])---------Rahul
print(D[3])---------Swagat
TRAVERSING A DICTIONARY
Traversing means accessing of each element of a dictionary.
Example:
D={1:’Rahul’,2:’Deepak’,3:’Swagat’}
for key in D:
print(key,’:’,D[key])
HOW TO ACCESS KEYS OR VALUES SIMULTANEOUSLY
D={1:’Rahul’,2:’Deepak’,3:’Swagat’}
print(D.keys())----------1,2,3
print(D.values())-------Rahul, Deepak, Swagat
MULTIPLE WAYS OF CREATING A DICTIONARY
1)Initialising a dictionary
D={25:’Rahul’,43:’Deepak’,29:’Swagat’}
Print(D)
2)Adding key:value pair
NAME={ }
NAME[101]=’R.K.SAHOO’
NAME[102]=’B.K.MISHRA’
print(NAME)------{101:’R.K.SAHOO’,102:’B.K.MISHRA’}
3)Creating a dictionary from name and value pairs
Emp=dict(name='Suresh', ‘salary’=50000,’age’=37)
print(Emp)
4)Specify keys and values separately
Emp=dict(zip( ('name', 'salary', 'age'), ('Suresh', 50000, 37) ))
print(Emp)---- {‘name’:’Suresh’,’salary’:50000,’age’:37}
5)By making key and value pair group
Emp=dict( [‘name’,’Suresh’], [‘salary’, 50000], [‘age’, 37] )
print(Emp)---- {‘name’:’Suresh’,’salary’:50000,’age’:37}
HOW TO ADD AN ELEMENT TO A DICTIONARY
D={1:’Rahul’,2:’Deepak’,3:’Swagat’}
D[4]=’Dhiren’
print(D)----{1:’Rahul’,2:’Deepak’,3:’Swagat’,4:’Dhiren’}
NESTING DICTIONARY
A dictionary within another dictionary is called nesting dictionary
Example:
Emp={‘R.K.Singh’: {‘age’:40,’salary’:60000}, ‘B.K.Dutta’:{‘age’:42,’salary’:55000} }
HOW CAN YOU UPDATE/MODIFY AN EXISTING ELEMENT OF A DICTIONARY?
Emp={‘name’:’Suresh’, ‘salary’:50000, ‘age’:37}
Emp[age]=39
print(Emp)---- {‘name’:’Suresh’,’salary’:50000,’age’:39}
CHECKING FOR EXISTENCE OF A KEY (in/not in)
Emp={‘name’:’Suresh’, ‘salary’:50000, ‘age’:37}
print(‘age’ in Emp)---------True
print(‘dept’ in Emp)-------False
print(‘age’ not in Emp)--------False
print(‘dept’ not in Emp)-------True
PRETTY PRINTING A DICTIONARY
import json
Emp={'name':'Suresh', 'salary':50000, 'age':37}
print(json.dumps(Emp,indent=2))
{
"Name":"Suresh",
"Salary":50000,
"Age":37
}
COUNTING THE FREEQUENCY OF ELEMENT TO A LIST USING DICTIONARY
Text="THE BBSR IS THE CAPITALOF THE ODISHA"
Word=Text.split()
print(Word)
print("Total Freequency=",Word.count("THE"))
DICTIONARY FUNCTIONS/METHODS
i)len()-It will print the length of a dictionary.
Emp={'name':'Suresh', 'salary':50000, 'age':37}
print(len(Emp))---------3
Emp[‘dept’]=’sales’
print(len(Emp))-------4
ii)get()-It will print the value of a given key.
Emp={'name':'Suresh', 'salary':50000, 'age':37}
print(Emp.get(‘salary’))--------50000
iii)items()-It will return both key and value as a sequence.
Emp={'name':'Suresh', 'salary':50000, 'age':37}
S=Emp.items()
for key,val in S:
print(key,val)
OUTPUT:
‘name’:’Suresh’
‘salary’:50000
‘age’:37
iv)keys()-It will print all the keys together.
Emp={'name':'Suresh', 'salary':50000, 'age':37}
print(Emp.keys())---------[‘name’,’salary’,’age’]
v)values()-It will print all the values together.
Emp={'name':'Suresh', 'salary':50000, 'age':37}
print(Emp.values())---------[‘Suresh’,50000,37]
HOW TO CREATE A DICTIONARY USING fromkeys() FUNCTION?
Example1:
D=dict.fromkeys((10,20,30), (40,50,60))
print(D)----{10:(40,50,60), 20:(40,50,60),30:(40,50,60)}
Uses of setdefault() method/function-It adds a new element at the end.
Example1:
Marks={1:50, 2:100, 3:200, 4:300}
Marks.setdefault(5,400)
print(Marks)------{1:350, 2:423, 3:411, 4:300, 5:320}
Example2:
Marks={1:50, 2:100, 3:200, 4:300}
Marks.setdefault(5)
print(Marks)------- {1:350, 2:423, 3:411, 4:300, 5:None}
Uses of update() method/function
Example:
Emp1={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
Emp2={“Name”:”B.K.Mishra”,”Salary”:90000,”Dept”:”Sales”}
Emp1.update(Emp2)
print(Emp1)
OUTPUT:
{'Name': 'B.K.Mishra', 'Salary': 90000, 'age': 43, 'Dept': 'Sales'}
HOW CAN YOU MAKE TRUE COPY OF A DICTIONARY USING copy() function?
Example:
Emp1={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
Emp2=Emp1.copy()
print(Emp1)------- {“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
print(Emp2)------- {“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
HOW TO DELETE AN ELEMENT USING del keyword?
Emp={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
del Emp[‘Salary’]
print(Emp)--- {“Name”:”R.K.sahoo”, “age”:43}
HOW TO DELETE AN ELEMENT USING pop() FUNCTION?
Emp={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
Emp.pop(‘Salary’)
print(Emp)--- {“Name”:”R.K.sahoo”, “age”:43}
HOW TO DELETE THE LAST ELEMENT FROM THE DICTIONARY USING popitem() FUNCTION?
Emp={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
Emp.popitem()
Output:
(‘age’,43)
print(Emp)---- {“Name”:”R.K.sahoo”, “Salary”:85000}
HOW TO MAKE EMPTY THE ENTIRE DICTIONAR USING clear() FUNCTION?
Emp={“Name”:”R.K.sahoo”, “Salary”:85000,”age”:43}
Example1:
Emp.clear()
print(Emp)
Output:
{}
Example2:
Emp={"Name":"R.K.sahoo", "Salary":85000,"age":43}
del Emp
print(Emp)
output:
name ‘Emp’ is not defined
HOW TO SORT A DICTIONARY USING sorted() FUNCTION?
Emp={15:94,7:96,10:91}
Emp1=sorted(Emp)
Emp2=sorted(Emp,reverse=True)
print(Emp1)
print(Emp2)
USES OF min(), max(), and sum() FUNCTIONS
min()-It will print the very smallest value of the dictionary.
Roll={15:94,7:96,10:91}
Print(min(Roll)
Output: 7
max()-It will print the very largest value of the dictionary.
Roll={15:94,7:96,10:91}
Print(max(Roll)
Output: 15
sum()-It will find sum of all the values of the dictionary.
Roll={15:94,7:96,10:91}
print(sum(Roll)
Output: 32
-O-
Dictionary-Type C programming: (Page No-493)
Q1.WAP to enter names of the employees and their salaries as input and store them in a
dictionary.
Ans.
D={}
for i in range(3):
k=input("Enter the name: ")
v=int(input("Enter the salary: "))
D[k]=v
print(D)
Q2.WAP to count the number of times the character appears in a given string.
Ans.
s=input("enter a string: ")
ch=input("enter the chracter to be searched: ")
ctr=s.count(ch)
print(ctr)
Q3.Input a number then print it in words.
Hint: Use a dictionary for number(0-9) as keys and word as value
D={0:’Zero’,1:’One’,2:’Two’,……………….9:’Nine}
Example:
Input-725
Output-Seven Two Five
Ans.
D={'0':'Zero','1':'One','2':'Two','3':'Three','4':'Four','5':'Five','6':'Six','7':'Seven','8':'Eight','9':'Nine'}
n=input("Enter a number in digits: ")
for i in n:
print(D[i],end=' ')
Q4. Repeteadly asks the user to enter the team name and how many games the team has own and
how many they lost. Store these information in a dictionary where the keys are team names and
the values are [wins,losses].
a)Allow user to enter team name and print out the teams winning percentage.
Ans.
b)Create a list whose entries are the number of wins each team.
Ans.
c)Create a list of of all those teams that have winning records.
Ans.
Q5. Write a program that repeatedly asks the user to enter the product name and prices. Store all
of these in a dictionary whose keys are the product names and whose values are the prices.
When the user is done entering products and prices, allow them to repeatedly enter a product
name and print the corresponding price or a message if the product is not in the dictionary.
Ans.
D={}
ch='y'
while ch=='y' or ch=='Y':
k=input("Enter the product name: ")
v=int(input("Enter the price: "))
D[k]=v
ch=input("Want to enter more(y/n): ")
print(D)
#SEARCHING PRODUCT AND DISPLAYING ITS PRICE
pn=input("Enter the product whose price u want to see: ")
if pn in D:
print(D[pn])
else:
print("product not available")
Q6. Create a dictionary whose keys are month names and whose values are the number of days in
the corresponding months.
(a)Enter the month name and display how many days are there.
Ans.
D={'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}
mn=input("Enter a month name: ")
print(mn,"has",D[mn],"days")
print(sorted(D))
for i in D:
if D[i]==31:
print(i)
D1=sorted(D)
print(D1)
(b)Print out all the keys in alphabetical order.
Ans.
D={'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}
L=D.keys()
L=sorted(L)
print(L)
(c)Print out all the months with 31 days.
Ans.
D={'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}
for key in D:
if(D[key]==31):
print(key)
(d)Print all the (key:value) pairs sorted by the number of days in each month.
Ans.
D={'January':31,'February':28,'March':31,'April':30,'May':31,'June':30,
'July':31,'August':31,'September':30,'October':31,'November':30,'December':31}
for key in D:
if(D[key]==28):
print(key,':',D[key])
for key in D:
if(D[key]==30):
print(key,':',D[key])
for key in D:
if(D[key]==31):
print(key,':',D[key])
Q7. Can you store the details of 10 students in a dictionary at the same time? Details includes Roll,
Name and Marks, Grade etc. Give example to support your answer.
Ans.
D1={‘Roll’:1,’Name’:’Rahul’,’Marks’:94,’Grade’:’C’}
Assign 9 more records of student like this
Print(D)
OR
D={}
for i in range(1,3):
k1=input("Enter key : ")
v1=int(input("Enter value: "))
D[k1]=v1
k2=input("Enter the key: ")
v2=input("Enter value: ")
D[k2]=v2
k3=input("Enter the key: ")
v3=input("Enter value: ")
D[k3]=v3
k4=input("Enter the key: ")
v4=input("Enter value: ")
D[k4]=v4
print()
print(D)
Q8. Given a dictionary X={‘k1’:’v1,’k2’:v2,k3:v3}, Create another dictionary with opposite mapping
as follows:
Y={‘v1’:’k1’,’v2’:’k2’,’v3’:’k3’}
Example:
D={k1:v1,k2:v2,k3:v3,k4:v4}
D={v1:k1,v2:k2,v3:k3,k4:v4}
Ans.
D={'Roll':1,'Name':'Ravi','class':'XI'}
print(D)
D1={}
for key in D:
D1[D[key]]=key
D=D1
print(D)
Q9.Given two dictionaries d1 and d2. Write a program that lists the overlapping keys of two
dictionaries i.e. list if a key of d1 is also a key of d2. List these keys.
Ans.
d1={1:11,2:22,3:33,4:44,5:55}
d2={6:66,7:77,1:111,2:222,8:88,5:555}
for key1 in d1:
for key2 in d2:
if key1==key2:
print(key1)
Q10.WAP that checks if two same values in a dictionary have different keys. That is, for dictionary
D1={‘a’:10,’b’:20,’c”:10}, the program should display ‘two keys have same values’
D2={‘a’:10,’b’:20,’c”:30}, the program should display ‘no keys have same values’
Ans.
d={'a':10,'b':20,'c':10}
ctr=0
for k1 in d:
for k2 in d:
if(d[k1]==d[k2]):
ctr+=1
if(ctr>1):
print(ctr,"keys have same value")
break
Q11.WAP to check if a dictionary is present in another dictionary i.e. if
D1={1:11, 2:12}
D2=[1:11,2:12,3:13,4:14,5:15}
Then d1 is present in d2
Ans.
D1={1:11, 2:12}
D2={1:11,2:12,3:13,4:14,5:15}
ctr=0
for key1 in D1:
for key2 in D2:
if key1==key2 and D1[key1]==D2[key2]:
ctr+=1
if(ctr==len(D1)):
print("D1 is present in D2")
else:
print("D2 is not present in D2")
Q12.A dictionary D1 has in the form of list of numbers. Write a program to create a new dictionary
D2 having same keys as D1 but values as the sum of the list elements.
Example:
d1={'A':[1,2,3],'B':[4,5,6]}
the d2 should be
d2={‘A’:6,’B’:15}
Ans.
d1={'A':[1,2,3],'B':[4,5,6]}
d2={}
for key in d1:
d2[key]=sum(d1[key])
print("d1=",d1)
print("d2=",d2)
-O-