Professional Documents
Culture Documents
Dictionaries
Dictionaries
{Key:value}
dict3 = {'Mohan':95,'Ram':89,'Suhel':92}
dict3 = {'Mohan':95,'Ram':89,'Suhel':92}
Ram 89
Mohan 92
Suhel 95
Mapping/hash table
Internally, the key:value pairs of a dictionary are associated with one another with some internal function (called hash-
function). This way of linking is called mapping.
Creating a Dictionary
You can convert the sequence returned by keys() and values() functions by
using list() as shown below:
>>>list(dict1.keys())
['Mohan', 'Ram', 'Suhel']
values()
Deletes the item with the given key. To delete the dictionary from the memory
we write: del Dict_name
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85} It returns KeyError if key is
>>> del dict1['Ram'] not existing in the
>>> dict1 dictionary
{'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> d={1:2,3:4,5:6}
>>> dict1 >>> del d[3],d[5]
>>> d
{'Suhel': 92, 'Sangeeta': 85} {1: 2}
>>> del dict1 >>>
>>> dict1
NameError: name 'dict1' is not defined
clear()
‘Not here’
Can give integer value too instead of message
M=Car.pop(“Color”, -1)
-1
Works on LIFO principle
as tuple of
key and
value
popitem() takes no argument
Xii d 28/8
as tuple of
key and
value
str(dict)
Return a printable string representation of a dictionary
Result of sorted
function typecasted to
dictionary
Extend/Update dictionary with new key:value pairs
>>> d1={}
>>> val1=d1.setdefault(30,'r')
>>> val2=d1.setdefault(30,'rr')
>>> val3=d1.setdefault(40)
>>> print(val1,val2,val3)
Predict the output????
>>> d1={}
>>> val1=d1.setdefault(30,'r')
>>> val2=d1.setdefault(30,'rr')
>>> val3=d1.setdefault(40)
>>> print(val1,val2,val3)
r r None
Predict the output????
>>> new_dict={}
>>> for i in range(5):
new_dict.setdefault(i)
>>> print(new_dict)
Predict the output????
>>> new_dict={}
>>> for i in range(5):
new_dict.setdefault(i)
>>> print(new_dict)
{0: None, 1: None, 2: None, 3: None, 4: None}
Will fetch max/min
key value pair
Will fetch only
max/min key
Lowest
Lowest
For min(), max() and sum() functions to work, the dictionary keys must be of homogenous types
>>> d1={(1,2):'one',(3,4):'two'}
>>> d2={'Green House':20,'Blue House':30}
>>> d3={41:'N',12:'S',32:'A'} >>> min(d1),min(d2),min(d3),min(d4)
((1, 2), 'Blue House', 12, 1.5)
>>> d4={1.5:'N',3.5:'s'} >>> max(d1),max(d2),max(d3),max(d4)
((3, 4), 'Green House', 41, 3.5)
>>> sum(d1)
Traceback (most recent call last):
Consider the declaration File "<pyshell#22>", line 1, in <module>
of 4 different dictionaries sum(d1)
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
>>> sum(d2)
>>> t1=(2,1)
>>> t2=(2,0)
Traceback (most recent call last):
>>> min(t1,t2) File "<pyshell#23>", line 1, in <module>
(2, 0) sum(d2)
>>> t1=(2,1,3) TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> t2=(2,1) >>> sum(d3)
>>> min(t1,t2) 85 sum() function worked with dictionaries
(2, 1) d3 and d4 as these dictionaries have
>>> sum(d4)
key types compatible for addition
5.0
Try!!!!!
>>> numbers={1:111,2:222,3:333,4:444}
>>> m1=max(numbers)
>>> m2=min(numbers)
>>> m3=max(numbers.values())
>>> m4=min(numbers.values())
>>> m5=sum(numbers)
>>> m6=sum(numbers.values())
>>> m7=max(numbers.items())
>>> print(m1,m2,m3,m4,m5,m6,m7)
Try!!!!!
>>> numbers={1:111,2:222,3:333,4:444}
>>> m1=max(numbers)
>>> m2=min(numbers)
>>> m3=max(numbers.values())
>>> m4=min(numbers.values())
>>> m5=sum(numbers)
>>> m6=sum(numbers.values())
>>> m7=max(numbers.items())
>>> print(m1,m2,m3,m4,m5,m6,m7)
4 1 444 111 10 1110 (4, 444)
When assignment operator is used
When copy() is used for copying
for copying list/tuple/dictionary,
list/tuple/dictionary, both objects refer
both objects refer to same memory Important to different memory locations
location concept
>>> l1=[1,2]
>>> l1=[1,2] >>> l2=l1.copy()
>>> l2=l1 >>> id(l1),id(l2)
>>> id(l1),id(l2) (58517344, 14788288)
(58516744, 58516744) >>> t1=(1,2)
>>> t1=(1,2) >>> t2=(3,4)
>>> t2=t1 >>> id(t1),id(t2)
>>> id(t1),id(t2) (14803272, 14769608)
(64851480, 64851480) >>> d1={1:2,3:4}
>>> d1={1:2,3:4} >>> d2=d1.copy()
>>> d2=d1 >>> id(d1),id(d2)
>>> id(d1),id(d2) (14757824, 14757728)
(60230368, 60230368)
Copy() :Creates separate copy of object in memory so that
changes made to one object are not reflected to other
>>> d1={1:2,3:4}
>>> d2=d1.copy()
>>> id(d1),id(d2) #deep copy
(66335968, 66336112) d1
>>> d3=d1 Note the id’s of the two
>>> id(d1),id(d3) #shallow copy dictionaries are same here d2=d1 {1:2,3:4}
(66335968, 66335968)
>>> d2
Using =
Using copy()
If the values are immutable, changes made to one are not reflected
in the other
If the values are mutable, changes made to one are reflected in the
other
>>> d={}
#to check a dictionary is empty or not >>> bool(d)
False
dict1 = {} >>> d={1:2}
>>> bool(d)
if not bool(dict1): True
print("Dictionary is empty")
Alternate code:
>>> d={}
>>> if len(d)==0:
print("empty")
#make a dictionary using constructor
dict1={1:'AMIT', 2:'VISHAL'}
dict2={3:'MOHAK'}
dict3 = {}
for d in (dict1, dict2):
dict3.update(d)
print(dict3)
#to create a dictionary where the keys are numbers between 1 to
10 and the values are square of keys
dict1=dict()
for x in range(1,11):
dict1[x]=x**2
print(dict1)
#to sum all the values of a dictionary
dict1 = {'data1':1,'data2':2,'data3':3}
r=sum(dict1.values())
print(r)
#to map two lists into a dictionary
OUTPUT
APPLE RED
GUAVA GREEN >>> d={'Subject': 'Informatics Practices', 'Class': 11}
MANGO YELLOW >>> sorted(d)
>>> ['Class', 'Subject']
Declare/create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the
key is the decimal number and the value is the corresponding number in words.
Declare/create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the
key is the decimal number and the value is the corresponding number in words.
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
Perform the following operations on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(a) Display the keys
Perform the following operations
on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(a) Display the keys
>>> ODD.keys()
dict_keys([1, 3, 5, 7, 9])
Perform the following operations
on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD.values()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
Perform the following operations
on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(g) Retrieve the value corresponding to the key 9
Perform the following operations on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(g) Retrieve the value corresponding to the key 9
>>> ODD.get(9)
'Nine'
Perform the following operations on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(h) Delete the item from the dictionary corresponding to the key 9
Perform the following operations on this dictionary:
>>> ODD =
{1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five',7: 'Seven', 9: 'Nine'}
(h) Delete the item from the dictionary corresponding to the key 9
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Write a program to enter names of employees and their
salaries as input and store them in a dictionary.
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000
'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
Write a program to enter names of employees and their
salaries as input and store them in a dictionary.
num = int(input("Enter the number of employees whose data to be
stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Write a program to create a dictionary to store and count the number of
times a character appears in a given string.
For example if the string is HelloWorld the dictionary should be
Enter a string: HelloWorld
{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}
Write a program to create a dictionary to store count the number of times a
character appears in a given string.
For example if the string is HelloWorld the dictionary should be
Enter a string: HelloWorld
{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}
st = input("Enter a string: ")
d = {} #creates an empty dictionary
for ch in st:
if ch in d: #if next character is already in the dictionary
d[ch] += 1
else:
d[ch] = 1 #if ch appears for the first time
print(d)
#OTHER WAY OF WRITING PREVIOUS QUESTION
#to create a dictionary from a string with frequency of letters
get() function returns None if key is not found. 0 would overwrite the default value None in
that case.
Write a program to create a dictionary where keys would be the
elements and their values would be the count of their frequency
Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two
Write a function to convert a number entered by the user into its
corresponding number in words. For example, if the input is 876 then
the output should be ‘Eight Seven Six’.
def convert(num):
numNames={0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six’,
7:'Seven',8:'Eight',9:'Nine’}
result = ‘’
for ch in num: Output:
key = int(ch) #converts character to integer Enter any number: 6512
value = numNames[key] The number is: 6512
result = result + ' ' + value The numberName is: Six Five One
Two
return result
>>> print(stateCapital.get("Bihar"))
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Bihar"))
Patna
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.keys())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.keys())
dict_keys(['AndhraPradesh', 'Bihar', 'Maharashtra', 'Rajasthan'])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.values())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.values())
dict_values(['Hyderabad', 'Patna', 'Mumbai', 'Jaipur'])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.items())
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.items())
dict_items([('AndhraPradesh', 'Hyderabad'), ('Bihar', 'Patna'),
('Maharashtra', 'Mumbai'), ('Rajasthan', 'Jaipur')])
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(len(stateCapital))
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(len(stateCapital))
4
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print("Maharashtra" in stateCapital)
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print("Maharashtra" in stateCapital)
True
>>>
>>> stateCapital = {"AndhraPradesh":"Hyderabad",
"Bihar":"Patna","Maharashtra":"Mumbai",
"Rajasthan":"Jaipur"}
>>> print(stateCapital.get("Assam"))
???
d={'a':5,'b':2,'c':10,'d’:7}
sorted(d.values(), reverse=True)[:3]
OUTPUT
[10, 7, 5]
Predict the output, if any??
>>>d={[1,2]: “abc”}
>>>d
Predict the output, if any??
>>>d={[1,2]: “abc”}
>>>d
:
TypeError:unhashable type: ‘list’
The above error always means that you have tried to assign a
key with mutable type and Python dictionaries do not allow
this.
Storing a dictionary inside another dictionary is called Nesting Dictionaries
nesting of dictionaries.
A dictionary contains details of two workers with their names as
Note: You can store a
keys and other details in the form of dictionary as value. WAP to dictionary as a value only,
print the workers’ information in records format. inside a dictionary. You cannot
have a key of dictionary
>>> emp={'John':{'age':25,'salary':20000},'Divya':{'age':35,'salary':30000}} type…why???...only
>>> for key in emp: immutable types can form the
print("Employee",key,':') keys of a dictionary.
print("Age:",emp[key]['age'])
print("Salary:",emp[key]['salary'])
Employee John :
Age: 25
Salary: 20000
Employee Divya :
Age: 35
Salary: 30000
>>>
WAP to read key(name) and age and salary of n employees in a
dictionary(nested)
=============== RESTART: C:/python37/class 11/dictionary/5.py
===============
Enter nameJohn
Enter age25
Enter salary20000
Press y to continue adding more datay
Enter nameDivya
Enter age35
Enter salary30000
Press y to continue adding more datan
{'John': {'Age’: 25, 'Salary’: 20000}, 'Divya': {'Age': 35, 'Salary': 30000}}
>>>
=============== RESTART:
WAP to read key(name) and age and salary of n C:/python37/class
employees in a dictionary(nested) 11/dictionary/5.py
===============
def create_nested_dictionary(): Enter nameJohn
emp={}
Enter age25
while True:
Enter salary20000
ag_sal={}
nm=input("Enter name") Press y to continue adding more
ag=int(input("Enter age")) datay
sl=eval(input("Enter salary")) Enter nameDivya
ag_sal['Age']=ag Enter age35
ag_sal['Salary']=sl Enter salary30000
emp[nm]=ag_sal Press y to continue adding more
ch=input("Press y to continue adding more datan
data") {'John': {'Age’: 25, 'Salary’:
if ch not in 'yY': 20000}, 'Divya': {'Age': 35,
break
'Salary': 30000}}
print(emp)
>>>
Write a menu driven program to display all the records of the dictionar
1:create
2:display all
3:search by name2
John 25 20000
Divya35 30000
1:create
2:display all
3:search by name
Write a menu driven program to display all the records of the
dictionary created in the above program.
1:create
2:display all
3:search by name2
John 25 20000
Divya35 30000
1:create
2:display all
3:search by name
def display_dict():
for name in emp:
print(name,emp[name]['Age'],emp[name]['Salary'],sep='\t')
Extend the above program to read a name of an employee, search and
display his all details. Display the error message if name is not found
{'Divya': {'Age': 25, 'Salary': 20000}, 'John': {'Age': 35, 'Salary': 30000}}
1:create
2:display all
3:search by name3
Enter name of the employee whose record is to be searchedJohn
inside if
Name John
Age 35 Salary 30000
1:create
2:display all
3:search by name3
Enter name of the employee whose record is to be searchedAakash
Aakash not found in the dictionary
Extend the above program to read a name of an employee, search and
display his all details. Display the error message if name is not found
def search_by_name():
nm=input("Enter name of the employee whose record is to be
searched")
for key in emp:
if nm==key:
print("inside if")
print("Name",nm)
print("Age",emp[nm]['Age'],"Salary",emp[nm]['Salary'],sep='\t')
break
else:
print("{} not found in the dictionary".format(nm))
Write a function update_sal(amt) to increase the salary of all the employees
by amt. Display the original and the updated dictionary
1:create
2:display all
3:search by name
4.update sal4
Enter the amount by which salary of all the employees is to be updated500
original dictionary
John 25 20000
Divya 35 30000
Records updated. Now the updated dictionary is
John 25 20500
Divya 35 30500
Write a function update_sal(amt) to increase the salary of all the employees
by amt. Display the original and the updated dictionary
def update_sal(amt):
print("original dictionary")
display_dict()
for key in emp:
emp[key]['Salary']+=amt
print("Records updated. Now the updated dictionary is")
display_dict()
Write a function update_sal_specific(name,amt) to increase the salary of
particular employee by amt. Display the original and the updated dictionary
{'John': {'Age': 25, 'Salary': 20000}, 'Divya': {'Age': 35, 'Salary': 30000}, 'Meeta': {'Age': 20,
'Salary': 25000}}
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee5
Enter name of the employee whose sal needs to be updatedDivya
Enter amount by which sal needs to be updated1200
Records updated. Now the updated dictionary is
John 25 20000
Divya 35 31200
Meeta 20 25000
Write a function update_sal_specific(name,amt) to increase the salary of
particular employee by amt. Display the original and the updated dictionary
def update_sal_specific(name,amt):
for key in emp:
if key==name:
emp[key]['Salary']+=amt
print("Records updated. Now the updated dictionary is")
display_dict()
break
else:
print("{} not found in the dictionary".format(name))
Write a function to read a name of the employee and delete the record of that employee.
{'John': {'Age': 25, 'Salary': 20000}, 'Divya': {'Age': 35, 'Salary': 30000}, 'Reena': {'Age': 20, 'Salary': 25000}}
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee
6.Delete an employee6
Enter name of the employee whose record needs to be deletedDivya
Employee deleted. Now the updated dictionary is
John 25 20000
Reena 20 25000
1:create
2:display all
3:search by name
4.update sal
5. update sal of specific employee
6.Delete an employee6
Enter name of the employee whose record needs to be deletedaakash
aakash not found in the dictionary
Write a function to read a name of the employee and delete the record of that employee.
def del_emp(name):
for key in emp:
if key==name:
del emp[key]
print("Employee deleted. Now the updated dictionary is")
display_dict()
break
else:
print("{} not found in the dictionary".format(name))
def create_nested_dictionary(): print("Age",emp[nm]['Age'],"Salary",emp[nm]['Salary'],sep='\t')
ag_sal={} break
while True: else:
ag_sal={} print("{} not found in the dictionary".format(nm))
nm=input("Enter name")
ag=int(input("Enter age")) def update_sal(amt):
sl=eval(input("Enter salary")) print("original dictionary")
ag_sal['Age']=ag display_dict()
ag_sal['Salary']=sl for key in emp:
emp[nm]=ag_sal emp[key]['Salary']+=amt
ch=input("Press y to continue adding more data") print("Records updated. Now the updated dictionary is")
if ch not in 'yY': display_dict()
break
print(emp)
def display_dict():
for name in emp:
print(name,emp[name]['Age'],emp[name]['Salary'],sep='\t’)
def search_by_name():
nm=input("Enter name of the employee whose record is to be
searched")
for key in emp: Complete program in two slides
if nm==key:
print("inside if")
print("Name",nm)
def update_sal_specific(name,amt): name\n4.update sal\n5. update sal of specific
for key in emp: employee\n6.Delete an employee"))
if key==name: if choice==1:
emp[key]['Salary']+=amt create_nested_dictionary()
print("Records updated. Now the updated dictionary elif choice==2:
is") display_dict()
display_dict() elif choice==3:
break search_by_name()
else: elif choice==4:
print("{} not found in the dictionary".format(name)) amt=eval(input("Enter the amount by which salary of all
the employees is to be updated"))
def del_emp(name): update_sal(amt)
for key in emp: elif choice==5:
if key==name: nm=input("Enter name of the employee whose sal needs
del emp[key] to be updated")
print("Employee deleted. Now the updated dictionary amt=eval(input("Enter amount by which sal needs to be
is") updated"))
display_dict() update_sal_specific(nm,amt)
break elif choice==6:
else: nm=input("Enter name of the employee whose record
print("{} not found in the dictionary".format(name)) needs to be deleted")
del_emp(nm)
emp={} else:
while True: break
WAP to create a dictionary d by swapping the keys and values of
dictionary d1
If
>>> dict1={1:'a',2:'b’}
Then
>>> dict2
{'a': 1, 'b': 2}
>>>
WAP to create a dictionary d by swapping the keys and values of
dictionary d1
>>> dict1={1:'a',2:'b'}
>>> dict2={}
>>> for key in dict1:
dict2[dict1[key]]=key
>>> dict2
{'a': 1, 'b': 2}
>>>
Finding the frequency of values of a dictionary
d={'p1':60,'p2':30,'p3':50,'p4':60,'p5':30,'p6':10}
df={}
t=tuple(d.values())
for v in t:
if v not in df:
df[v]=t.count(v)
print(df)
print("now sorted data")
print(dict(sorted(df.items())))