Dictionaries in Python are used to store information that comes in key-value pairs. A dictionary contains a key and its value.
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)
We created a dictionary named countries
, set “usa”
as the key, and “washington”
as the value.
{'usa': 'Washington'}
The code returned a dictionary, as expected.
Now, how do we dynamically add another 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.
Now, let’s add "Ghana"
as the key, and "Accra"
as the value to the dictionary.
countries={"usa":"washington"}countries["Ghana"] = "Accra"print(countries)
countries
.Ghana
into a square bracket, and assigning Accra
as the value.Similarly, we can add many other key:value
pairs in our dictionary.