Does a dictionary have to be created with initial values?


#1

Question

In this exercise, the dictionary is created with initial values. Does a dictionary always have to be created with initial values?

Answer

No, a dictionary does not have to be created with initial values. You can create an empty dictionary using either of the two methods shown here.

locations = {}
# OR
locations = dict()

To add values to the dictionary you can use the index syntax (square brackets) or call the update() function on the dictionary and pass data to be populated into the dictionary. The update method can be used to populate multiple key/values to the dictionary. The syntax for these is shown below.

locations['Paris'] = 100
locations.update({"London": 75})
locations.update({"New York": 83, "Vancouver" : 110})

print(locations)
# {'Paris': 100, 'London': 75, 'New York': 83, 'Vancouver': 110}