Chap 4 Python dictionary.
A python dictionary is a collection of elements where each element is a combination of key and value pair. Each
value is associated with a unique key.
All the key value pairs are associated with a unique key.All the key value pairs are enclosed in curly braces.
Dictionaries are mutable, unordered collection of elements in the form of key-value pairs which are enclosed
in curly braces.
Example of dictionary
dict1={1:"one",2:"two",3:"three"}
print(dict1)
dict2={"a":"apple","b":"ball","c":"cat"}
print(dict2)
Characteristics of python dictionary
The combination of key and value pair is called key value pair
Key and its values are separated by colon (:)
Different key value pair are separated by comma
Keys are unique for each value
Keys of dictionary must be of immutable type string and number
We can change the value but not keys
Method to create empty dictionary
A={ } #is an empty dictionary
A=dict()
Method to create dictionary at run time
1 .Write a program to enter roll number and names of five students and store the data in dictionary
dict3={ }
n=int(input ("how many numbers you want to enter"))
for i in range(n):
rollno=int(input("enter rollno"))
name=input("enter name")
dict3[rollno]=name
print(dict3)
Output:- how many numbers you want to enter3
enter rollno1
enter namepooja
{1: 'pooja'}
enter rollno2
enter namelekha
{1: 'pooja', 2: 'lekha'}
enter rollno3
enter namesudha
{1: 'pooja', 2: 'lekha', 3: 'sudha'}
2. Write a program to store bookid,bookname and price of three books and store the data in dictionary
dict3={ }
for i in range(3):
bookid=int(input("enter book id"))
bookname=input("enter book name")
price=input("enter book price")
dict3[bookid]=bookname,price
print(dict3)
Output:-
enter book id1
enter book namecomputer science
enter book proce700
{1: ('computer science', '700')}
enter book id2
enter book nameinformatic practices
enter book proce500
{1: ('computer science', '700'), 2: ('informatic practices', '500')}
enter book id3
enter book namemath
enter book proce600
{1: ('computer science', '700'), 2: ('informatic practices', '500'), 3: ('math', '600')}
Traversing a python dictionary
dict1={1:"one",2:"two",3:"three"}
for i in dict1:
print(i,dict1[i])
output:
1 one
2 two
3 three
How to append values in python dictionary
dict1={1:"one",2:"two",3:"three"}
dict1[4]="four"
print(dict1)
output:-
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
#join two dictioanries using update method
dict1={1:"one",2:"two",3:"three"}
dict2={"a":"apple","b":"ball","c":"cat"}
dict1.update(dict2)
print(dict1)
output:-
{1: 'one', 2: 'two', 3: 'three', 'a': 'apple', 'b': 'ball', 'c': 'cat'}
#update values in python dictioanry
dict2={1:"apple",2:"ball",3: "CAT"}
dict2[3]="elephant"
print(dict2)
OUTPUT:-
{1: 'apple', 2: 'ball', 3: 'elephant'}
#removing or deleting element from dictionary
dict2={1:"apple",2:"ball",3: "CAT",4:"car"}
del dict2[3]
print(dict2)
Output:- {1: 'apple', 2: 'ball', 4: 'car'}
Dictionary methods
Len():-
This function returns the length of dictionary means ,it returns the total number of key value pair present in the
dictionary. For example
Write a program to find legth of dictionary
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
print(len(dict1))
print(len(dict2))
output:-
{1: 'apple', 2: 'ball', 3: 'elephant'}
{1: 'apple', 2: 'ball', 4: 'car'}
4
2
Keys()
This function returns all the keys of dictionary in the form of list:For example
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
print(dict1.keys())
print(dict2.keys())
output:-
dict_keys([1, 2, 3, 4])
dict_keys([11, 12])
values()
This method returns all values of dictionary in the form of list.
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
print(dict1.keys())
print(dict2.keys())
output:-
dict_values(['one', 'two', 'three', 'four'])
dict_values(['apple', 'ball'])
items()
This function returns all the key value pair of dictionary in the form of list of tuples:
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
print(dict1.items())
print(dict2.items())
Output:-
dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
dict_items([(11, 'apple'), (12, 'ball')])
update()
This function joins two key value pair into one or we can say that is is join or merge two dictionaries.
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
dict1.update(dict2)
print(dict1)
Output:-
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 11: 'apple', 12: 'ball'}
Get()
This method returns value of the required key
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
print(dict1.get(2))
print(dict2.get(12))
output:-
two
ball
clear()
This function removes all items from the dictionary.
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
dict1.clear()
print(len(dict1))
print(len(dict2))
output:-
0
2
Note:- This function removes items from the dictionary it does not delete the dictionary
pop()
This function not only delete the element of required key but also return the deleted value
dict1={1:"one",2:"two",3:"three", 4:"four" }
dict2={ 11: "apple", 12: "ball"}
a=dict1.pop(2)
print(a)
dict2.pop(11)
print(dict2)
output:-
two
{12: 'ball'}
Board pattern questions:-
A school wants to maintain a dictionary student where roll number is the key and name is the value. Write a
program to:
Insert 3 students
Display all students
Delete one entry based on roll number
Ans:-
student = {}
student[1] = "Ali"
student[2] = "Riya"
student[3] = "John"
print("All Students:", student)
del student[2] # delete roll no 2
print("After Deletion:", student)
Identify and correct the error in the following code
1)student = {101:"Amit", 102:"Riya", 103:"John"}
print(student(101))
student.add(104:"Ali")
solution:-
student = {101:"Amit", 102:"Riya", 103:"John"}
print(student[101]) # use [] not ()
student[104] = "Ali" # use assignment, not add()
2)fruits = {'apple', 120, 'mango', 80}
print(fruits['apple'])
solution: -
fruits = {'apple': 120, 'mango': 80} # dictionary uses key: value
pairs
print(fruits['apple'])
3)data = {1: "One", 2: "Two", 3: "Three"}
print(data.get[2])
data.remove(3)
solution:-
data = {1: "One", 2: "Two", 3: "Three"}
print(data.get(2)) # get() uses ()
data.pop(3) # remove() not valid, use pop()
4) marks = {'Math':90, 'Science':88}
print(marks.keys[ ])
marks.append('English':85)
solution:-
marks = {'Math':90, 'Science':88}
print(marks.keys()) # keys() is a method
marks['English'] = 85 # append() invalid for dict
Predict the output:-
1)d = {'a':1, 'b':2, 'c':3}
print(len(d))
print(d.get('d', 0))
print('a' in d)
solution
3
0
True
2) info = {'Name':'Ali', 'Age':17, 'Class':11}
info['Age'] = info['Age'] + 1
print(info)
solution
{'Name': 'Ali', 'Age': 18, 'Class': 11}
3)d = {}
for i in range(3):
d[i] = i*i
print(d)
solution
{0: 0, 1: 1, 2: 4}
3)d = {'India': 'Delhi', 'Nepal': 'Kathmandu'}
d.update({'Sri Lanka':'Colombo'})
print(d.items())
solution
dict_items([('India', 'Delhi'), ('Nepal', 'Kathmandu'), ('Sri Lanka', 'Colombo')])
4)d = {'A':1, 'B':2, 'C':3}
print(d.get('B'))
print(d.get('D', -1))
print(len(d))
solution
�
2
-1
3
5) d = {'x':10, 'y':20, 'z':30}
print('y' in d)
print(d.pop('x'))
print(d)
solution
True
10
{'y': 20, 'z': 30}
6) d = {}
for i in range(1,4):
d[i] = i**2
print(d)
solution
{1: 1, 2: 4, 3: 9}
7) data = {'India':'Delhi', 'Nepal':'Kathmandu', 'Sri Lanka':'Colombo'}
print(data.keys())
print(data.values())
solution
dict_keys(['India', 'Nepal', 'Sri Lanka'])
dict_values(['Delhi', 'Kathmandu', 'Colombo'])
8) Write a program to create a dictionary where keys are numbers from 1 to 5 and values are their squares.
squares = {}
for i in range(1, 6):
squares[i] = i*i
print(squares)
output:-
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
9) Write a Python program that takes a dictionary of months and sales, then calculates the total sales.
sales = {'Jan': 45000, 'Feb': 52000, 'Mar': 61000}
solution
total = sum(sales.values())
print("Total Sales:", total)
output:-
Total Sales: 158000
10)Write a program to accept the key from the user and remove that dictionary if present
dict1={1:2,2:90,3:50}
K=int(input(“enter any key”)
If k in d1:
dict1.pop(k)
print(dict1)
else:
print(“key not found”)
11)write a program to remove duplicate values from dictionary.
dict1={1:”suresh”,2:”aman”,3:”suman”,4:”aman”}
dict2={ }
For k,v in dict1.items()
if v not in dict2.values()
dict2[k]=v
print (dict2)