Merging dictionary value lists in python

后端 未结 6 904
无人及你
无人及你 2020-11-29 10:27

I\'m trying to merge three dictionaries, which all have the same keys, and either lists of values, or single values.

one={\'a\': [1, 2], \'c\': [5, 6], \'b\'         


        
6条回答
  •  心在旅途
    2020-11-29 10:48

    One line solution (also handles for keys present in only one dict):

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

    Example 1:

    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]}

    Example 2:

    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']}

提交回复
热议问题