How to add items to a dictionary in Python
Overview
Dictionaries in Python are used to store information that comes in key-value pairs. A dictionary contains a key and its value.
Code example
For example, each country has its capital, and in this context, the different countries can be keys, whereas their respective capitals are their values.
Take a look at this code below:
countries={"usa":"washington"}print(countries)
Code explanation
We created a dictionary named countries, set “usa” as the key, and “washington” as the value.
Code output
{'usa': 'Washington'}
The code returned a dictionary, as expected.
Now, how do we dynamically add another item to a dictionary?
How to add an item to a dictionary
To add another country, for example, "Ghana", to the dictionary we created earlier, countries, we use a new index key and value.
Code example
Now, let’s add "Ghana" as the key, and "Accra" as the value to the dictionary.
countries={"usa":"washington"}countries["Ghana"] = "Accra"print(countries)
Code explanation
- Line 1: We create the dictionary
countries. - Line 2: We add a new key and value to the dictionary by putting the value
Ghanainto a square bracket, and assigningAccraas the value. - Line 3: We print the updated dictionary.
Similarly, we can add many other key:value pairs in our dictionary.