python dict.update vs.下标添加单个键/值对 [英] python dict.update vs. subscript to add a single key/value pair
问题描述
每个学期,我至少有一个Python学生使用dict.update()
添加单个键/值对,即:
Every semester I have at least one Python student who uses dict.update()
to add a single key/value pair, viz.:
mydict.update({'newkey':'newvalue'})
代替
mydict['newkey'] = 'newvalue'
我没有教授这种方法,也不知道他们在哪里找到这种方法的示例,但是我告诉他们不要这样做,因为它效率较低(大概创建了一个新的2元素字典),并且非标准.
I don't teach this method and I don't know where they're finding examples of this, but I tell them not to do it because it's less efficient (presumably creates a new 2-element dict) and because it's nonstandard.
老实说,我可以理解使用可见方法而不是使用这种语法的愿望-也许感觉与其他方法调用更加一致.但我认为这似乎是一种新手方法.
Honestly, I can understand the desire to use a visible method rather than this syntax - it perhaps feels more consistent with other method calls. But I think it looks like a newbie approach.
在这一点上,有没有人可以提供任何智慧?
Is there any wisdom anyone has to offer on this point?
推荐答案
基准测试表明您怀疑其性能影响是正确的:
A benchmark shows your suspicions of its performance impact appear to be correct:
$ python -m timeit -s 'd = {"key": "value"}' 'd["key"] = "value"'
10000000 loops, best of 3: 0.0741 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update(key="value")'
1000000 loops, best of 3: 0.294 usec per loop
$ python -m timeit -s 'd = {"key": "value"}' 'd.update({"key": "value"})'
1000000 loops, best of 3: 0.461 usec per loop
也就是说,它在我的机器上慢了大约六倍.但是,如果您需要最佳性能,那么Python已经不是您要使用的语言,因此,我只建议您使用这种情况下最易读的语言.在许多情况下,这是[]
的方式,尽管update
在这种情况下可能更具可读性:
That is, it's about six times slower on my machine. However, Python is already not a language you'd use if you need top performance, so I'd just recommend use of whatever is most readable in the situation. For many things, that would be the []
way, though update
could be more readable in a situation like this:
configuration.update(
timeout=60,
host='example.com',
)
…或类似的东西.
…or something like that.
这篇关于python dict.update vs.下标添加单个键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!