Should we use update or value assignment?

In #2 of this exercise we are told to do the following:

Without changing the definition of the dictionary oscar_winners, change the value associated with the key “Best Picture” to “Moonlight”.

I used the following code:

#option one is to use the update method:
oscar_winners.update({"Best Picture": "Moonlight"})

#option two is this value assignment:
oscar_winners["Best Picture"] = "Moonlight"

Both of these appear to generate the same output. But for the purposes of this exercise, which is more correct? Does one ‘change the definition’ of oscar_winners and one not?

What is the difference and in what cases should I use one method over the other?

Thanks for reading!

No ‘should’ about it. Either method is fine. The advantage of using update can be seen when we have multiple key/value pairs to insert or update. The subscript method is one key/value at a time. update takes a dictionary or an iterable such as a list of tuples.

1 Like