有没有办法在Python 2.7中附加两个词典?

时间:2017-03-02 22:45:10

标签: python python-2.7 dictionary

我想添加两个词典,而不是第二个更新第一个词典。该值将是单个变量或列表。 我想要实现的目标:

输入:

x = {"a": [1] }
y = {"a": [2, 3], "b": [2] }

输出:

z = {"a": [1,2,3], "b": [2] }

如果它也可以接受单个int而不是前面提到的列表,那将会很棒:

输入:

x = {"a": 1 }
y = {"a": [2, 3], "b": [2] }

输出:

z = {"a": [1,2,3], "b": [2] }

所以寻找

z = append_dicts(x, y)

这就是我想出来的。

def merge_two_dicts(x, y):
    """Given two dicts, append them into a new dict."""
    for key in x:
        if isinstance(x[key], list):
            y[key].extend(x[key])
        else:
            y[key].append(x[key])
    return y

3 个答案:

答案 0 :(得分:1)

单行(适用于Python2.7)

dict([(k, x.get(k,[])+y.get(k,[])) for k in set(x)|set(y)])

和一个非常漂亮的可以消化非名单

 dict([(k, [a for b in [x.get(k,[])]+[y.get(k,[])] for a in (b if isinstance(b, list) else [b])]) for k in set(x)|set(y)])

答案 1 :(得分:0)

这可以为您提供解决方案:

def append_dicts(x, y):
    z = dict(y)
    for k, v in x.items():
        if isinstance(v, list):
            z[k].extend(v)
        if isinstance(v, int):
            z[k].append(v)
    return z


x = {"a": [1] }
y = {"a": [2, 3], "b": [2] }
print(append_dicts(x, y))
# {'a': [2, 3, 1], 'b': [2]}

x = {"a": 1 }
y = {"a": [2, 3], "b": [2] }
print(append_dicts(x, y))
# {'a': [2, 3, 1], 'b': [2]}

答案 2 :(得分:0)

累积功能:一个接受重复,一个不接受...

#!/usr/bin/python

from collections import defaultdict
from sets import Set

def combineUnique(input_dict_list):
    accumulating_dict = defaultdict(Set)
    for d in input_dict_list:
        for key,values in d.items():
            for value in values:
                accumulating_dict[key].add(value)
    return accumulating_dict

def combineWithDuplicates(input_dict_list):
    accumulating_dict = defaultdict(list)
    for d in input_dict_list:
        for key,value in d.items():
            accumulating_dict[key].extend(value)
    return accumulating_dict

if __name__=='__main__':

    x = {"a": [1, 2] }
    y = {"a": [2, 3], "b": [2] }


    print "With duplicates..."
    print combineWithDuplicates([x,y])

    print "Unique..."
    print combineUnique([x,y])

...返回

With duplicates...
defaultdict(<type 'list'>, {'a': [1, 2, 2, 3], 'b': [2]})
Unique...
defaultdict(<class 'sets.Set'>, {'a': Set([1, 2, 3]), 'b': Set([2])})