How To Add Values to a Python Dictionary

Estimated reading time: 1 minute

As part of our ongoing series about Python Interview questions, we discussed how you would create an empty dictionary.

In this posting, we are going to go through the different ways you could add values to your dictionary.

In the below code, we have created an empty dictionary for you.

So as we go down through lines 5 and 6, you can see that we have created two key names and assigned them values. This has the result of populating those key-value pairs to empty_dict1.

Now as you build out your Python logic, you may just want to update the dictionary by using empty_dict1.update(Add key-value pair here).

Finally, there is the option to just use an if statement that checks if the values you want to add exist already, and if not it adds them in.

#How do add values to a python dictionary
empty_dict1 = {}
empty_dict2 = dict()

empty_dict1['Key1'] = '1'
empty_dict1['Key2'] = '2'

#Example1 - #Appending values to a python dictionary
empty_dict1.update({'key3': '3'})

#Example2 - Use an if statement
if "key4" not in empty_dict1:
    empty_dict1["key4"] = '4'
    print("Key exists, so not added")

{'Key1': '1', 'Key2': '2'}
{'Key1': '1', 'Key2': '2', 'key3': '3'}
{'Key1': '1', 'Key2': '2', 'key3': '3', 'key4': '4'}

Leave a Reply

Your email address will not be published. Required fields are marked *