change198
change198

Reputation: 2065

how to merge dictionaries of lists with unique key values

I have below dictionaries of lists:

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

And my below piece of code is working just as expected.

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))

which gives me

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

But my question is how to print the final result to have unique values, e.g. here EventType has same values. So, in final result i would only expect the final result to be

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

Is there anyway I can achieve this?

Upvotes: 0

Views: 37

Answers (2)

Ajay A
Ajay A

Reputation: 1068

Try this

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))

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Use set

Ex:

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))

Output:

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

Upvotes: 1

Related Questions