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.

16 Likes

I had this same question when it was brought up on a code review why I chose update over [ ] =. I didn’t really have an answer and I use both ways all the time. However, trying to defend my choice a little I decided to do some performance testing (which didn’t go my way :rofl:). I would say code readability is the biggest defense since generally, that is more important than a little performance gain. However, updating via subscription seems to be about twice to three times as fast at least.

popos:~$ python3 -m timeit 'd={"k":1}; d.update({"k":2})'
5000000 loops, best of 5: 91.2 nsec per loop
popos:~$ python3 -m timeit 'd={"k":1}; d["k"] = 2'
5000000 loops, best of 5: 43 nsec per loop
popos:~$ python3 -m timeit 'd={"k":1}; d.update({"k":2, "j":4})'
2000000 loops, best of 5: 181 nsec per loop
popos:~$ python3 -m timeit 'd={"k":1}; d["k"] = 2; d["j"] = 4'
5000000 loops, best of 5: 54.9 nsec per loop

It’s always a little tricky to do timings on such a small set of operations (and small objects). One of the biggest differences you have here is that with your update method you create two entirely different dictionary objects and then combine them, the subscript syntax just modifies a single dictionary (each piece of {key:value} syntax creates a new dictionary).

So I’d be inclined to use .update when I have already have the relevant objects, be that two dictionaries or a dictionary and something storing key-value pairs which is the same guidance as provided above.

1 Like