Adding and deleting from Dictionaries

python console outputTo add or replace keys and values in a Dictionary we write the following code.

d={}#Create an empty dictionary
d[1]="One"#Add 1:One 
d[2]="Two"#Add 2:Two
print(d)#Print the Dictionary
del d[2]#del Element with key 2
print(d)#Print again
d[1]="एक"#Change value at key 1
print(d)


Output

Adding elements with a loop.
The following code creates a list of the first 10 factorials.

factorials={0:1}
f=1
for i in range(1,11):
    f=f*i
    factorials[i]=f
    
print(factorials)

key=int(input("Enter the key = "))
print(factorials.get(key))

Output
python console output

Pop can be used for the purpose of deleting elements.
Remember that it is an instance function while del is static.

d={}
for i in range(1,11):
    d[i]=i
print(d)
print(d.pop(7))
print(d)


Output

python console output

Leave a Reply