This tutorial will discuss how to add to a value in a dictionary in Python.
Suppose we have a dictionary that contains student data, where the name is the key (a string) and the age is the value (an integer). Like this,
# Student data dictionary with # names as keys and ages as values student_data = { "Varun Sharma": 21, "Renuka Singh": 19, "Sachin Roy": 20 }
Now, if we want to add a numeric value to the value field of a specific key, we need an integer value. For example, consider we have a dictionary of student data where the key is the name and the value is the age of the student. Now, if we want to add 5 to the age of student “Renuka Singh”, we will select the value from the dictionary by passing the key “Renuka Singh” into the square brackets of the dictionary. It will return a reference to the value field of that key-value pair. Then, we add 5 to it, which will increment the value of that key-value pair by 5.
Let’s see the complete example,
# Student data dictionary with # names as keys and ages as values student_data = { "Varun Sharma": 21, "Renuka Singh": 19, "Sachin Roy": 20 } # Add a value to an existing value student_data["Renuka Singh"] += 5 # Print the updated dictionary print(student_data)
Output
{'Varun Sharma': 21, 'Renuka Singh': 24, 'Sachin Roy': 20}
However, if we try to add an integer value to the value field of a key that does not exist in the dictionary (basically passing a key into the square brackets that does not exist in the dictionary), it will cause a KeyError because we are trying to access a key that does not exist in the dictionary.
Like in the below example, we are trying to incremenet the value of a Key that does not exists in the Dictionary.
Frequently Asked:
Let’s see the complete example,
# Student data dictionary with # names as keys and ages as values student_data = { "Varun Sharma": 21, "Renuka Singh": 19, "Sachin Roy": 20 } # Add a value to an existing value # Will Cause KeyError student_data["Bob Singh"] += 5 # Print the updated dictionary print(student_data)
Output
Traceback (most recent call last): File "./temp.py", line 11, in <module> student_data["Bob Singh"] += 5 KeyError: 'Bob Singh'
Summary
Today, we learned how to add to a value in a dictionary in Python.