To merge two dictionaries of list in Python

前端 未结 6 1486

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 13:58

    One line solution:

    { key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }
    

    Example 1:

    x={1:['a','b','c']}
    y={1:['d','e','f'],2:['g']}
    { key:x.get(key,[])+y.get(key,[]) for key in set(list(x.keys())+list(y.keys())) }
    

    Output:

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

    Example 2:

    one = {'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
    two = {'a': [2.4, 3.4], 'c': [5.6, 7.6], 'd': [3.5, 4.5]}
    { key:one.get(key,[])+two.get(key,[]) for key in set(list(one.keys())+list(two.keys())) }
    

    Output:

    {'a': [1, 2, 2.4, 3.4], 'b': [3, 4], 'c': [5, 6, 5.6, 7.6], 'd': [3.5, 4.5]}

提交回复
热议问题