合并几个python词典 [英] merging several python dictionaries

查看:25
本文介绍了合并几个python词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须合并 python 字典列表.例如:

I have to merge list of python dictionary. For eg:

dicts[0] = {'a':1, 'b':2, 'c':3}
dicts[1] = {'a':1, 'd':2, 'c':'foo'}
dicts[2] = {'e':57,'c':3}

super_dict = {'a':[1], 'b':[2], 'c':[3,'foo'], 'd':[2], 'e':[57]}    

我写了以下代码:

super_dict = {}
for d in dicts:
    for k, v in d.items():
        if super_dict.get(k) is None:
            super_dict[k] = []
        if v not in super_dict.get(k):
            super_dict[k].append(v)

能否更优雅/优化地呈现?

注意我在 SO 上发现了另一个问题,但它是关于合并两个字典.

Note I found another question on SO but its about merging exactly 2 dictionaries.

推荐答案

您可以直接遍历字典——无需使用 range.dict 的 setdefault 方法查找一个键,如果找到则返回该值.如果未找到,则返回一个默认值,并将该默认值分配给键.

You can iterate over the dictionaries directly -- no need to use range. The setdefault method of dict looks up a key, and returns the value if found. If not found, it returns a default, and also assigns that default to the key.

super_dict = {}
for d in dicts:
    for k, v in d.iteritems():  # d.items() in Python 3+
        super_dict.setdefault(k, []).append(v)

此外,您可以考虑使用 defaultdict.这只是通过调用函数来自动 setdefault 以在未找到键时返回默认值.

Also, you might consider using a defaultdict. This just automates setdefault by calling a function to return a default value when a key isn't found.

import collections
super_dict = collections.defaultdict(list)
for d in dicts:
    for k, v in d.iteritems():  # d.items() in Python 3+
        super_dict[k].append(v)

此外,正如 Sven Marnach 敏锐地观察到的那样,您似乎不希望列表中的值重复.在这种情况下, set 会得到你想要的:

Also, as Sven Marnach astutely observed, you seem to want no duplication of values in your lists. In that case, set gets you what you want:

import collections
super_dict = collections.defaultdict(set)
for d in dicts:
    for k, v in d.iteritems():  # d.items() in Python 3+
        super_dict[k].add(v)

这篇关于合并几个python词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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