Python字典中的更新方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17547507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update method in Python dictionary
提问by Max Kim
I was trying to update values in my dictionary, I came across 2 ways to do so:
我试图更新字典中的值,我遇到了两种方法:
product.update(map(key, value))
product.update(key, value)
What is the difference between them?
它们之间有什么区别?
采纳答案by Martijn Pieters
The difference is that the second method does not work:
不同之处在于第二种方法不起作用:
>>> {}.update(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: update expected at most 1 arguments, got 2
dict.update()
expects to find a iterable of key-value pairs, keyword arguments, or another dictionary:
dict.update()
期望找到一个可迭代的键值对、关键字参数或另一个字典:
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return
None
.
update()
accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs:d.update(red=1, blue=2)
.
使用其他键/值对更新字典,覆盖现有键。返回
None
。
update()
接受另一个字典对象或键/值对的可迭代对象(作为元组或其他长度为 2 的可迭代对象)。如果指定关键字参数,字典,然后用这些键/值对更新:d.update(red=1, blue=2)
。
map()
is a built-in method that produces a sequence by applying the elements of the second (and subsequent) arguments to the first argument, which must be a callable. Unless your key
object is a callable and the value
object is a sequence, your first method will fail too.
map()
是一个内置方法,它通过将第二个(和后续)参数的元素应用于第一个参数来生成一个序列,第一个参数必须是可调用的。除非您的key
对象是一个可调用value
对象并且该对象是一个序列,否则您的第一个方法也会失败。
Demo of a working map()
application:
一个工作map()
应用程序的演示:
>>> def key(v):
... return (v, v)
...
>>> value = range(3)
>>> map(key, value)
[(0, 0), (1, 1), (2, 2)]
>>> product = {}
>>> product.update(map(key, value))
>>> product
{0: 0, 1: 1, 2: 2}
Here map()
just produces key-value pairs, which satisfies the dict.update()
expectations.
这里map()
只生成键值对,满足dict.update()
预期。