Python 3映射字典更新方法到其他字典的列表 [英] Python 3 map dictionary update method to a list of other dictionaries

查看:241
本文介绍了Python 3映射字典更新方法到其他字典的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python 2 I can do the following:

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

在Python 3中获得KeyError:

In Python 3 in get a KeyError:

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

我希望在Python 3中实现与在Python 2中相同的行为.

I would like to achieve the same behavior in Python 3 as in Python 2.

我了解Python 3中的map将返回一个迭代器(延迟评估和其他功能),必须对其进行迭代才能更新字典.

I understand that map in Python 3 will return an iterator (lazy evaluation and whatnot), which has to be iterated for the dictionary to be updated.

我假设d['c']键查找会以某种方式触发地图迭代,而事实并非如此.

I had assumed the d['c'] key lookup would trigger the map iteration somehow, which is not the case.

是否存在一种无需编写for循环即可实现此行为的pythonic方法, 与地图相比,我觉得它很冗长.

Is there a pythonic way to achieve this behavior without writing a for loop, which I find to be verbose compared to map.

我曾经考虑过使用列表推导:

I have thought of using list comprehensions:

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

但是它似乎不是pythonic的.

But it does not seem pythonic.

推荐答案

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

As you note, map in Python 3 creates an iterator, which doesn't (in and of itself) cause any updates to occur:

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

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

To force the map to be fully evaluated, you could pass it to list explicitly:

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


但是,作为> Python中的新增功能的相关部分3 说:

由于map()的副作用而特别棘手 功能;正确的转换是使用常规的for循环 (因为创建列表会很浪费).

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).

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

In your case, this would look like:

for extra in extras:
    d.update(extra)

不会导致不必要的None列表.

which doesn't result in an unnecessary list of None.

这篇关于Python 3映射字典更新方法到其他字典的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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