您何时会在dict.update方法的字典上使用键值对? [英] When would you use a key-value pair over a dict for the dict.update method?

查看:75
本文介绍了您何时会在dict.update方法的字典上使用键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到您可以做两件事来更新字典,并且它们似乎具有相同的结果:

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,

但是再说一次,如果我想更新str类型以外的其他键:

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

此外,您可以存储 dict ,因此,如果需要通过变量进行更新:

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

这篇关于您何时会在dict.update方法的字典上使用键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆