gpt4 book ai didi

python - "Flattening"字典列表

转载 作者:IT老高 更新时间:2023-10-28 20:35:23 26 4
gpt4 key购买 nike

所以我的目标是:

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

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

我得到的一个方法是:

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

还有更好的pythonic方式吗?

最佳答案

为什么要复制?

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

A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can accessed or updated using the maps attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.

您只需要这个(更改名称以遵守Python naming conventions):

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'])

关于python - "Flattening"字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com