How to change or add elements in a dictionary?
* Dictionary is mutable. We can add new items or change the value of existing items using an assignment operator.
* If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
Example:1
n={“roll”:101,”name”:”Ajay”,”age”:21,”per”:99}
print(n)
n[“roll”]=500
print(n)
n[“name”]=”komal”
print(n)
n[“age”]=25
print(n)
n[“per”]=100
print(n)
Output:
{‘roll’: 101, ‘name’: ‘Ajay’, ‘age’: 21, ‘per’: 99}
{‘roll’: 500, ‘name’: ‘Ajay’, ‘age’: 21, ‘per’: 99}
{‘roll’: 500, ‘name’: ‘komal’, ‘age’: 21, ‘per’: 99}
{‘roll’: 500, ‘name’: ‘komal’, ‘age’: 25, ‘per’: 99}
{‘roll’: 500, ‘name’: ‘komal’, ‘age’: 25, ‘per’: 100}
n={"roll":101,"name":"Ajay","age":21,"per":99} print(n) n["roll"]=500 print(n) n["name"]="komal" print(n) n["age"]=25 print(n) n["per"]=100 print(n)
{'roll': 101, 'name': 'Ajay', 'age': 21, 'per': 99} {'roll': 500, 'name': 'Ajay', 'age': 21, 'per': 99} {'roll': 500, 'name': 'komal', 'age': 21, 'per': 99} {'roll': 500, 'name': 'komal', 'age': 25, 'per': 99} {'roll': 500, 'name': 'komal', 'age': 25, 'per': 100} >>>
Example:2
n={“accno”:1001,”name”:”Sanjay”,”Balance”:36000}
print(n)
n[“accno”]=5000
print(n)
n[“name”]=”Kapil”
print(n)
n[“Balance”]=50000
print(n)
Output:
{‘accno’: 1001, ‘name’: ‘Sanjay’, ‘Balance’: 36000}
{‘accno’: 5000, ‘name’: ‘Sanjay’, ‘Balance’: 36000}
{‘accno’: 5000, ‘name’: ‘Kapil’, ‘Balance’: 36000}
{‘accno’: 5000, ‘name’: ‘Kapil’, ‘Balance’: 50000}
>>>
n={"accno":1001,"name":"Sanjay","Balance":36000} print(n) n["accno"]=5000 print(n) n["name"]="Kapil" print(n) n["Balance"]=50000 print(n)
{'accno': 1001, 'name': 'Sanjay', 'Balance': 36000} {'accno': 5000, 'name': 'Sanjay', 'Balance': 36000} {'accno': 5000, 'name': 'Kapil', 'Balance': 36000} {'accno': 5000, 'name': 'Kapil', 'Balance': 50000} >>>