如何合并具有唯一键值的列表字典

时间:2020-08-13 10:01:10

标签: python-3.x

我有以下列表的字典:

dict1 = {'SourceName': ['PUICUI'], 'EventType': ['XYX'], 'TableName': ['XYX__ct'], 'KeyIndex': ['XYX', 'ZXX']}
dict2 = {'SourceName': ['PUICI2'], 'EventType': ['XYX'], 'TableName': ['ZXX__ct1']}

下面的代码按预期运行。

def combineDictList(*args):
    result = {}
    for dic in args:
        for key in (result.keys() | dic.keys()):
            if key in dic:
                result.setdefault(key, []).extend(dic[key])
    return result

print(combineDictList(dict1, dict2))

这给了我

{'TableName': ['XYX__ct', 'ZXX__ct1'], 'SourceName': ['PUICUI', 'PUICI2'], 'KeyIndex': ['XYX', 'ZXX'], 'EventType': ['XYX', 'XYX']}

但是我的问题是如何将最终结果打印为具有唯一值,例如这里EventType具有相同的值。 所以,在最终结果中,我只会期望最终结果是

{'TableName': ['XYX__ct', 'ZXX__ct1'], 'SourceName': ['PUICUI', 'PUICI2'], 'KeyIndex': ['XYX', 'ZXX'], 'EventType': ['XYX']}

反正我能做到吗?

2 个答案:

答案 0 :(得分:2)

尝试一下

def combineDictList(*args):
    result = {}
    for dic in args:
        for key in (result.keys() | dic.keys()):
            if key in dic:
                result.setdefault(key, []).extend(dic[key])
                result[key] = list(set(result[key]))

    return result

print(combineDictList(dict1, dict2))

答案 1 :(得分:1)

使用set

例如:

dict1 = {'SourceName': ['PUICUI'], 'EventType': ['XYX'], 'TableName': ['XYX__ct'], 'KeyIndex': ['XYX', 'ZXX']}
dict2 = {'SourceName': ['PUICI2'], 'EventType': ['XYX'], 'TableName': ['ZXX__ct1']}


def combineDictList(*args):
    result = {}
    for dic in args:
        for k, v in dic.items():
            result.setdefault(k, set()).update(v)

    # If you need values as list
    # result = {k: list(v) for k, v in result.items()}
    return result

print(combineDictList(dict1, dict2))

输出:

{'EventType': {'XYX'},
 'KeyIndex': {'ZXX', 'XYX'},
 'SourceName': {'PUICI2', 'PUICUI'},
 'TableName': {'ZXX__ct1', 'XYX__ct'}}