To merge two dictionaries of list in Python

前端 未结 6 1485

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:15

    You could do this:

    final = {}
    dicts = [x,y]
    
    for D in dicts:
        for key, value in D:
            final[key] = final.get(key,[]).extend(value)
    

    final.get(key,[]) will get the value in final for that key if it exists, otherwise it'll be an empty list. .extend(value) will extend that list, empty or not, with the corresponding value in D, which is x or y in this case.

提交回复
热议问题