Python 3 映射字典更新方法到其他字典列表

标签 python python-3.x python-2.7 dictionary map-function

<分区>

在 Python 2 中,我可以执行以下操作:

>> d = {'a':1}
>> extras = [{'b':2}, {'c':4}]
>> map(d.update, extras)
>> d['c']
>> 4

在 Python 3 中得到一个 KeyError:

>> d = {'a':1}
>> extras = [{'b':2}, {'c':4}]
>> map(d.update, extras)
>> d['c']
>> KeyError: 'c'

我想在 Python 3 中实现与在 Python 2 中相同的行为。

我知道 Python 3 中的 map 将返回一个迭代器(惰性求值等等),必须迭代它才能更新字典。

我原以为 d['c'] 键查找会以某种方式触发 map 迭代,但事实并非如此。

是否有一种 pythonic 方法可以在不编写 for 循环的情况下实现这种行为, 与 map 相比,我发现它过于冗长。

我想到了使用列表理解:

>> d = {'a':1}
>> extras = [{'b':2}, {'c':4}]
>> [x for x in map(d.update, extras)]
>> d['c']
>> 4

但它看起来不像pythonic。

最佳答案

正如您所注意到的,Python 3 中的 map 创建了一个迭代器,它(本身)不会导致任何 update 发生:

>>> d = {'a': 1}
>>> extras = [{'b':2}, {'c':4}]
>>> map(d.update, extras)
<map object at 0x105d73c18>
>>> d
{'a': 1}

要强制对 map 进行全面评估,您可以将其显式传递给 list:

>>> list(map(d.update, extras))
[None, None]
>>> d
{'a': 1, 'b': 2, 'c': 4}

但是,作为What's new in Python 3的相关栏目|说:

Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

在您的情况下,这看起来像:

for extra in extras:
    d.update(extra)

这不会导致不必要的 None 列表。

关于Python 3 映射字典更新方法到其他字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30000391/

相关文章:

python - QTableWidget 可以有多少行或多少列?

python - 从 S3 将 CSV 数据加载到 Jupyter Notebook

python - 通过 View (Django)的 celery 任务返回为待处理,但可以通过终端

python - 没有名为 tesseract 的模块

python - 比较两个 CSV 文件之间的值并写入第三个 CSV 文件

python - Django 设置.py 错误

python - 如何解决 ValueError : unsupported pickle protocol: 4

python-3.x - 如何在图像中找到对象的方向?

python - PyQt : Compiling date/time into window title

python - 如何调整 xmlrpclib 来解释自定义类型?