Pythonic获得字典联合的方法

时间:2016-06-06 07:10:28

标签: python dictionary

是否有更好的/ pythonic方式来执行以下操作:

我有一个合并字典的函数:

def merge_dicts(a, *dict_args):
    for dictionary in dict_args:
        for k, v in dictionary.items():
            if k not in a:
                a[k] = v

    return a

以下是一个示例运行:

a = {'A': 1, 'B': 2}
b = {'B': 3, 'C': 4}
c = merge_dicts(a, b) # {'A': 1, 'B': 2, 'C': 4}

我正在使用python2.7。

2 个答案:

答案 0 :(得分:2)

您可以使用update。由于早期的dicts具有优先级,因此您必须以相反的顺序更新,并使用a last:

进行更新
def merge_dicts(a, *dict_args):
    d = {}
    for dictionary in reversed(dict_args):
        d.update(dictionary)
    d.update(a)
    return d

或使用itertools.chain

作为单行
from itertools import chain

def merge_dicts(a, *dict_args):
    # chain (key, value) items in order of increasing priority
    return dict(chain.from_iterable(d.iteritems() for d in dict_args[::-1]+(a,)))

> merge_dicts(a, b)
{'A': 1, 'C': 4, 'B': 2}

如果我可以添加,为什么不从功能签名中删除a

def merge_dicts(*dict_args):
    return dict(chain.from_iterable(d.iteritems() for d in dict_args[::-1]))
# If you provide 0 or 1 dict,
# this will return an empty dict or the single dict (a copy thereof) itself

答案 1 :(得分:1)

您不需要检查字典中是否存在键,因为您希望通过循环遍历字典列表来保留第一个可以使用字典理解的键:

{k: v for d in list_of_dict[::-1] for k, v in d.items()}

Python会用新的密钥替换存在密钥,每次遇到重复密钥时,由于你向后循环遍历列表,它会在聚合字典中找到第一个密钥。

根据您的示例:

>>> {k: v for d in l[::-1] for k, v in d.items()}
{'A': 1, 'C': 4, 'B': 2}
相关问题