简体   繁体   中英

When would you use a key-value pair over a dict for the dict.update method?

I've noticed that you can do two things to update a dictionary, and that they seem to have the same outcome:

a = {}
a.update({'foo': 1})

a = {}
a.update(foo = 1)

Both lead to the result of a dictionary that looks like:

{'foo': 1}

Is there any reason to prefer using a dictionary or a key/value pair for the update method? Are they completely functionally equivalent or is there a 'gotcha' that one syntax might cause?

There could be different reasons for using one over the other. For example:

>>> d = {}
>>> d.update(a=2)        # looks much cleaner
>>> d.update({'a': 2})   # We need to unnecessarily write a few more characters,

But then again, if I want to update a key other than of str type:

>>> d = {}
>>> d.update(2='a')      # Gives a syntax error
>>> d.update({2: 'a'})   # is the only way

Furthermore, you can store a dict , so if you needed to update via a variable:

>>> u = {'a': 2}
>>> d = {}
>>> d.update(u)          # clean
>>> d.update(**u)        # Essentially same as using keyword argument form, but unnecessary

Another scenario, when you are updating some key manually, but others from a variable, keyword argument form is cleaner and shorter:

>>> u = {'a': 2}
>>> d = {}
>>> d.update(b=3, **u)
# Whereas to use `dict` form:
>>> d.update({'b': 3, **u})   # Introduces unnecessary clutter

Is there any reason to prefer using a dictionary or a key/value pair for the update method?

That you already have one, eg if you have a base dict and an other dict (from a constant, or a parameter) then dict1.update(dict2) makes perfect sense.

Also makes sense if you're generating the second dict dynamically eg dict1.update(zip(keys, values)) .

Are they completely functionally equivalent or is there a 'gotcha' that one syntax might cause?

The "keyword arguments" form only works with string keys (in Python 3, in Python 2 it unintentionally worked with non-string keys as well). Even using the mapping-unpacking form. It also can not be used with literal keywords eg

d.update(assert=3)

is a syntax error.

More generally

The keyword form is useless on its own

It can make sense to add keywords to an update call with a positional argument eg

d.update(d2, key=value)

as you're already piggybacking on a call which is necessary. However

d.update(key=value)

is generally[0] just a more complicated, more limiting, and slower way of writing

d['key'] = value
```:
```sh
❯ python3 -mtimeit -s "d = {'a': 'b'}" "d.update(c='d', e='f', g='h')"
2000000 loops, best of 5: 202 nsec per loop
❯ python3 -mtimeit -s "d = {'a': 'b'}" "d['c']='d'; d['e']='f'; d['g']='h'"
5000000 loops, best of 5: 62.2 nsec per loop

I don't remember the numbers (and they probably changed with recent releases as there have been optimisations to literal dicts) but when I benched this a few years back you'd need several dozen keys before you broke even.

[0] it can be useful in the rare case where you need to update a dict in an expression context eg a lambda body, I don't think I've ever been in that situation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM