我如何将字典列表组合到像键组合的字典列表中

时间:2019-11-27 03:16:38

标签: python dictionary defaultdict

我要输入以下信息:

mycounter = [{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]                                                                                                                                                        
#[{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]

并实现此所需的输出:

[{6: ['Credit card']}, {2: ['Debit card', 'Check']}]

我的尝试如下,但与所需的输出不匹配。感谢您的帮助。谢谢。

temp = list(zip([*map(lambda d: next(iter(d.keys())), mycounter)], [*map(lambda d: next(iter(d.values())), mycounter)]))  

c = collections.defaultdict(list)
for a,b in temp:
   c[a].extend(b)

final = [dict(c)]
# Close, but not quite the desired output since it's should be two dict objects, not one
# [{6: ['Credit card'], 2: ['Debit card', 'Check']}]

我在stackoverflow上的搜索找到了与提供None值相结合的解决方案,但没有像我要的那样。我的问题与之前的另一个类似问题的输入有所不同。

3 个答案:

答案 0 :(得分:2)

为了提供选项,这是使用defaultdict的替代版本,我发现它更易于使用,尤其是随着复杂度的增加:

from collections import defaultdict
result = defaultdict(list)
for d in mycounter:
    for k, v in d.items():
        result[k] += v

In : result
Out: defaultdict(list, {6: ['Credit card'], 2: ['Debit card', 'Check']})

Defaultdict在大多数情况下都像dict,但是如果有必要,可以使用以下命令将其转换为

In : dict(result)
Out: {6: ['Credit card'], 2: ['Debit card', 'Check']}

答案 1 :(得分:1)

一种选择是制作单个字典,然后在以下之后将其分成单个键值对:

mycounter = [{6: ['Credit card']}, {2: ['Debit card']}, {2: ['Check']}]                                                                                                                                                        

res = {}
for d in mycounter:
    for k, v in d.items():
        res.setdefault(k, []).extend(v)
[{k:v} for k, v in res.items()]
# [{6: ['Credit card']}, {2: ['Debit card', 'Check']}]

答案 2 :(得分:1)

这与another question非常相似;唯一的区别是,您希望每个键/值对都在其自己的字典中。这是一个使用理解和迭代工具的适应性解决方案:

from itertools import chain

def merge_dicts(*dicts):
    return [
        { k: list(chain.from_iterable( d[k] for d in dicts if k in d )) }
        for k in set(chain.from_iterable(dicts))
    ]