To merge two dictionaries of list in Python

前端 未结 6 1475

There are two dictionaries

x={1:[\'a\',\'b\',\'c\']}
y={1:[\'d\',\'e\',\'f\'],2:[\'g\']}

I want another dictionary z which is a merged one

6条回答
  •  一整个雨季
    2020-12-19 14:12

    Here is a Python 3 solution for an arbitrary number of dictionaries:

    def dict_merge(*dicts_list):
        result = {}
        for d in dicts_list:
            for k, v in d.items():
                result.setdefault(k, []).append(v)
        return result
    

    Note that this solution may create lists with duplicate values. If you need unique values, use set():

    def dict_merge(*dicts_list):
        result = {}
        for d in dicts_list:
            for k, v in d.items():
                result.setdefault(k, set()).add(v)
        return result
    

提交回复
热议问题