To merge two dictionaries of list in Python

前端 未结 6 1476

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

    0 讨论(0)
  • 2020-12-19 14:02
    for k, v in x.items():
    if k in y.keys():
        y[k] += v
    else:
        y[k] = v
    

    Loop through dictionary getting keys and values, check if the key already exists, in which case append, else add new key with values. It won't work if your values are mixed data types that aren't lists, like you have.

       x={1:['a','b','c'], 3:['y']} 
    .. y={1:['d','e','f'],2:['g']} 
    ..  
    ..  
    .. for k, v in x.items(): 
    ..     if k in y.keys(): 
    ..         y[k] += v 
    ..     else: 
    ..         y[k] = v 
    ..      
    .. print y
    {1: ['d', 'e', 'f', 'a', 'b', 'c'], 2: ['g'], 3: ['y']}
    
    0 讨论(0)
  • 2020-12-19 14:03

    This is what worked for me :

    d1={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
    d2 = {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]}
    d3 = {}
    for k in d1.keys():
        d3.update( {k : []} )
        for i in d1[k]:
            d3[k].append(i)
        for j in d2[k]:
            d3[k].append(j)
    print(d3)
    

    I know it's a roundabout way of doing it, but the other methods didn't work when the dictionary values were ndarrays.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-19 14:15

    Counter() can be used in this case:

    >>> x={1:['a','b','c']}
    >>> y={1:['d','e','f'],2:['g']}
    >>> from collections import Counter
    >>> Counter(x) + Counter(y)
    Counter({2: ['g'], 1: ['a', 'b', 'c', 'd', 'e', 'f']})
    

    If desired result is a dict. You can use the following:

    z = dict(Counter(x) + Counter(y))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题