Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么';将键/值对的列表(或其他迭代器)添加到dict是一种python方式吗?_Python_Python 2.7_Dictionary - Fatal编程技术网

什么';将键/值对的列表(或其他迭代器)添加到dict是一种python方式吗?

什么';将键/值对的列表(或其他迭代器)添加到dict是一种python方式吗?,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,为了使用从列表、集合、生成器或dict转换的值构造dict,我使用dict理解 d = { r['name']:r for r in responses } 这里的响应是一个dict,我也可以使用一个列表,例如: d = { extract_the_key(r):extract_the_value for r in responses } 现在假设我已经有了dict。如何将相同的键值对添加到dict中 当然,我可以做到: for r in responses: d[extract_t

为了使用从列表、集合、生成器或dict转换的值构造dict,我使用dict理解

d = { r['name']:r for r in responses }
这里的
响应
是一个dict,我也可以使用一个列表,例如:

d = { extract_the_key(r):extract_the_value for r in responses }
现在假设我已经有了dict。如何将相同的键值对添加到dict中

当然,我可以做到:

for r in responses:
    d[extract_the_key(r)] = extract_the_value(r)
但这似乎不那么像蟒蛇,更丑陋。有没有一种惯用的方法


请注意,我可能已经有了dict,因为我已经在其中设置了一些值。但我可能已经拥有了它,因为它是
defaultdict
dict
的其他扩展。这意味着我不能仅仅使用新的值创建一个新的dict,然后以某种“理解风格”将两者结合起来。

你可以使用字典的
更新方法,例如

d.update((extract_the_key(r), extract_the_value(r)) for r in responses)
怎么样
dict.update(成对序列)