简体   繁体   English

使用带有 lambda 参数的 reduce 函数获取具有相同键的新字典

[英]Get a new dictionary with the same keys using reduce function with a lambda argument

I have a list of dictionaries like this.我有一个这样的字典列表。

fruit = [{"apple": 10, "pear": 20, "banana": 30, "strawberry": 50},
{"apple": 12, "pear": 5, "banana": 20, "strawberry": 5},
{"apple": 15, "pear": 26, "banana": 32, "strawberry": 8}]

Can I write an reduce function in one line(with lambda argument) to get a new dictionary with the same keys.我可以在一行中编写一个 reduce 函数(使用 lambda 参数)来获得一个具有相同键的新字典。 The value to each key of the new dictionary is the sum of all the values to the corresponding key.新字典的每个键的值是对应键的所有值的总和。 The expected output should be a dictionary as follows:预期的输出应该是一个字典,如下所示:

{'apple': 37.0, 'pear': 51.0, 'banana': 82.0, 'strawberry': 63.0}

Util-heavy approach: Util-heavy 方法:

from operator import add
from collections import Counter
from functools import reduce

reduce(add, map(Counter, fruit))
# Counter({'banana': 82, 'strawberry': 63, 'pear': 51, 'apple': 37})

Or maybe more instructive for the beginner, writing an add for two dicts:或者也许对初学者更有指导意义,为两个字典写一个add

def add(d1, d2):
    return {k: d1.get(k, 0) + d2.get(k, 0) for k in d1.keys() | d2.keys()}

reduce(add, fruit)

A dict-comprehension can do the work of merging two dicts like this: dict-comprehension 可以完成合并两个 dict 的工作,如下所示:

>>> from functools import reduce
>>> fruit = [{"apple": 10, "pear": 20, "banana": 30, "strawberry": 50},
...          {"apple": 12, "pear": 5, "banana": 20, "strawberry": 5},
...          {"apple": 15, "pear": 26, "banana": 32, "strawberry": 8}]
>>> reduce(lambda a, b: {k: a[k] + v for k, v in b.items()}, fruit)
{'apple': 37, 'pear': 51, 'banana': 82, 'strawberry': 63}

This does require that all dicts have the same keys, otherwise some will be dropped.这确实要求所有 dicts 具有相同的键,否则一些将被删除。 The more complete version is this, which does get pretty unwieldy as a reduce-lambda though:更完整的版本是这个,尽管它作为一个 reduce-lambda 确实变得非常笨拙:

reduce(lambda a, b: {k: a.get(k, 0) + b.get(k, 0) for k in a.keys() | b.keys()}, fruit)

The following approach uses a dict comprehension and no imports.以下方法使用字典理解而不使用导入。 I don't recommend to use it however:但是我不建议使用它:

{k: sum(f.get(k,0) for f in fruit) for k in {k for f in fruit for k in f}}
#                                           |                           |
#                                           +-- set of all fruit keys --+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM