2017-03-02 88 views
0

我想添加兩個字典,而不是更新第一個與第二個。該值將是單個變量或列表。 我想什麼來實現:有沒有辦法在Python 2.7中追加兩個字典?

輸入:

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

輸出:

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

這將是巨大的,如果它也能接受單個int,而不是隻列表如前所述:

I NPUT:

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 
+4

是的,這是可能的,但是這不是一個代碼編寫的服務。你嘗試過什麼嗎?發生了什麼? – jonrsharpe

+0

@vincent我通過列出的帖子閱讀,但該方法更新第一個字典,第二個字典丟失第一個字典的值。 – synergy

+2

@synergy您可能需要自行實施。你有什麼想法嗎? – sangheestyle

回答

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

一行代碼(在Pytho上工作) n2.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)]) 
+0

不錯!我知道那裏有一個單線!如果我看到它,我會花一分鐘來弄清它做了什麼。 – vincent

+0

謝謝保羅,很好的一班。 – synergy