- We can access data by using keys.
Example
Python
d={1:'ajay', 2:'amit', 3:'manish'}
print(d[1])
print(d[3])
Output
PowerShell
ajay
manish
- If the specified key is not available then we will get KeyError.
Example
Python
d={1:'ajay', 2:'amit', 3:'manish'}
print(d[4])
Output
PowerShell
KeyError: 4
- We can prevent this by checking whether key is already available or not by using in operator.
Example
Python
d={1:'ajay', 2:'amit', 3:'manish'}
if 4 in d:
print(d[4])
else:
print(d[3])
Output
PowerShell
manish
Question
Write a program to enter name and percentage marks in a dictionary and display information on the screen.
Example
Python
rec={}
n=int(input("Enter number of students: "))
i=1
while i <=n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
Output
PowerShell
Enter number of students: 3
Enter Student Name: suman
Enter % of Marks of Student: 60%
Enter Student Name: ajay
Enter % of Marks of Student: 70%
Enter Student Name: amit
Enter % of Marks of Student: 80%
Name of Student % of marks
suman 60%
ajay 70 %
amit 80%
Update Elements
Syntax
Python
d[key]=value
- If the key is not available then a new entry will be added to the dictionary with the specified key-value pair. If the key is already available then old value will be replaced with new value.
Example
Python
d={1:"ajay", 2:"amit", 3:"manish"}
print(d)
d[4]="suman"
print(d)
d[1]="seema"
print(d)
Output
PowerShell
{1: 'ajay', 2: 'amit', 3: 'manish'}
{1: 'ajay', 2: 'amit', 3: 'manish', 4: 'suman'}
{1: 'seema', 2: 'amit', 3: 'manish', 4: 'suman'
Delete Elements
There are three methods to delete elements.
del d[key]
- It deletes entry associated with the specified key.
- If the key is not available then we will get KeyError.
Example
Python
d={1:"ajay", 2:"amit", 3:"manish"}
print(d)
del d[1]
print(d)
del d[4]
Output
PowerShell
{1:"ajay",2:"amit",3:"manish"}
{2:"amit",3:"manish"}
KeyError: 4
d.clear()
- To remove all entries from the dictionary
Example
Python
d={1:"ajay", 2:"amit", 3:"manish"}
print(d)
d.clear()
print(d)
Output
PowerShell
{1:"ajay",2:"amit",3:"manish"}
{}
del d
- To delete total dictionary. We cannot access d after delete.
Example
Python
d={1:"ajay", 2:"amit", 3:"manish"}
print(d)
del d
print(d)
Output
PowerShell
{1:"ajay",2:"amit",3:"manish"}
NameError: name 'd' is not defined
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!