2013-04-30 152 views
0

所以我想嘗試和合並只有特定的鍵從一個字典到另一個這樣字典合併某些鍵

a = {'a':2, 'b':3, 'c':5} 
b = {'d':2, 'e':4} 
a.update(b) 
>>> a 
{'a': 2, 'c': 5, 'b': 3, 'e': 4, 'd': 2} # returns a merge of all keys 

但是說你只是想將鍵值對「D」:2,而不是全部在字典中的元素等你拿怎麼會變成這樣可能:

{'a': 2, 'c': 5, 'b': 3, 'd': 2} 

回答

2

如果你知道你想要b['d']更新a,使用此:

a['d'] = b['d'] 
0

我不知道我是否有問題。無論如何,如果你希望只更新與另一個鍵的字典了一些按鍵,你可以這樣做:

a['d'] = b['d'] 

,或者,如果你想更新多個鍵:

for to_update in keys_to_update: # keys_to_update is a list 
    a[to_update] = b[to_update] 
0

您可以使用以下片段:

a = {'a':2, 'b':3, 'c':5} 
b = {'d':2, 'e':4} 

desiredKeys = ('d',) 

for key, val in b.items(): 
    if key in desiredKeys: 
     a[key] = b[key] 

print(a) 

樣品將上述輸出:

{'d': 2, 'b': 3, 'c': 5, 'a': 2}