When working with dictionaries in Python, to add a key value pair to a dictionary, you just need to access the key and assign the value.
dictionary = {"bananas":4, "pears":5}
dictionary["apples"] = 6
print(dictionary)
#Output:
{"apples":6, "bananas":4, "pears":5}
In Python, dictionaries are a collection of key value pairs separated by commas. When working with dictionaries, it can be useful to be able to easily create new items.
We can easily create new key value pairs in a Python dictionary.
For example, if we have the following dictionary and want to create an “apples” key and assign it with the value 6, we can do so by assigning 6 to the key “apples”.
Below is an example in Python of how to add a key value pair to a dictionary.
dictionary = {"bananas":4, "pears":5}
dictionary["apples"] = 6
print(dictionary)
#Output:
{"apples":6, "bananas":4, "pears":5}
Replacing Values in a Dictionary in Python
If you already have a dictionary and want to replace a value in the dictionary, then you can do something similar to the above example.
We can easily replace values of keys in a Python dictionary.
To access the value of a specific key, you just need to call access it with the key name.
For example, if we have the following dictionary and want to get the value of the “apples” key, we can do so by accessing the item with the key “apples”.
dictionary = {"apples":3, "bananas":4, "pears":5}
print(dictionary["apples"])
#Output:
3
Then, if you want to replace the value and reassign a new value to a key, you can just use regular assignment.
Below is an example in Python of how to reassign and replace a value in a dictionary.
dictionary = {"apples":3, "bananas":4, "pears":5}
dictionary["apples"] = 6
print(dictionary)
#Output:
{"apples":6, "bananas":4, "pears":5}
Hopefully this article has been useful for learning how to add a key value pair to a dictionary using Python.