25

So my aim is to go from:

fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]

to

finalMap = {'apple': 'red', 'banana': 'yellow'}

A way I got is:

 from itertools import chain
 fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
 colour = list(chain.from_iterable([d.values() for d in fruitColourMapping]))
 return dict(zip(fruits, colour))

Is there any better more pythonic way?

4

9 回答 9

39

为什么要复制?

在 Python 3 中,您可以使用新的ChainMap

ChainMap 将多个 dicts(或其他映射)组合在一起以创建一个可更新的视图。
底层映射存储在列表中。该列表是公开的,可以使用maps属性访问或更新。没有其他状态。查找连续搜索底层映射,直到找到一个键。相反,写入、更新和删除仅对第一个映射进行操作。

您所需要的就是这个(更改名称以遵守Python 命名约定):

from collections import ChainMap
fruit_colour_mapping = [{'apple': 'red'}, {'banana': 'yellow'}]
final_map = ChainMap(*fruit_colour_mapping)

然后你可以使用所有正常的映射操作:

# print key value pairs:
for element in final_map.items():
    print(element)

# change a value:
final_map['banana'] = 'green'    # supermarkets these days....

# access by key:
print(final_map['banana'])
于 2013-03-29T13:25:58.873 回答
32
finalMap = {}
for d in fruitColourMapping:
    finalMap.update(d)
于 2013-03-26T21:26:06.993 回答
31
{k: v for d in fruitColourMapping for k, v in d.items()}
于 2013-03-26T21:28:41.263 回答
14

而不是解构和重建,只需复制和更新:

final_map = {}
for fruit_color_definition in fruit_color_mapping:
    final_map.update(fruit_color_definition)
于 2013-03-26T21:26:15.040 回答
5

方法

使用reduce将每个 dict 应用于空的初始化程序。由于dict.update总是返回None,所以使用它d.update(src) or d来给出reduce所需的返回值。

代码

final_dict = reduce(lambda d, src: d.update(src) or d, dicts, {})

测试

>>> dicts = [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'a': 6}]
>>> final_dict = reduce(lambda d, src: d.update(src) or d, dicts, {})
>>> final_dict
{'a': 6, 'c': 4, 'b': 3}
于 2013-03-30T02:01:42.780 回答
5
dict(d.items()[0] for d in fruitColourMapping)
于 2013-03-26T21:26:51.510 回答
5

给定

d1, d2 = [{'apple': 'red'}, {'banana': 'yellow'}]

代码

在 Python 3.5 中,引入了字典解包(参见PEP 448):

{**d1, **d2}
# {'apple': 'red', 'banana': 'yellow'}

在 Python 3.9 中,引入了合并运算符

d1 | d2
# {'apple': 'red', 'banana': 'yellow'}
于 2017-09-14T09:35:58.357 回答
4

我想出了一个有趣的一个班轮。

>>> a = [{"wow": 1}, {"ok": 2}, {"yeah": 3}, {"ok": [1,2,3], "yeah": True}]
>>> a = dict(sum(map(list, map(dict.items, a)), []))
>>> a
{'wow': 1, 'ok': [1, 2, 3], 'yeah': True}
于 2020-07-30T03:01:06.483 回答
2

你也可以试试:

finalMap = dict(item for mapping in fruitColourMapping for item in mapping.items())

于 2017-10-20T22:31:25.447 回答