2016-09-16 113 views
-1

比方說,我有一本字典,像這樣:更新/追加到詞典

x = {'age': 23, 
    'channel': ['a'], 
    'name': 'Test', 
    'source': {'data': [1, 2]}} 

和一個類似像:

y = {'age': 23, 
    'channel': ['c'], 
    'name': 'Test', 
    'source': {'data': [3, 4], 'no': 'xyz'}} 

,如果我用這個x.update(y)我會失去'channel'例如以前的信息..如何在不同的時候添加值,並在字典中不存在時添加鍵值?

最終結果應該是:

{'age': 23, 
'channel': ['a', 'c'], 
'name': 'Test', 
'source': {'data': [1, 2, 3, 4], 'no': 'xyz'}} 

我差點與此:

for a,b in y.iteritems(): 
    try: 
     x[a] = x[a] + y[a] 
    except: 
     x[a] = y[a] 

但失敗了的時候才發現字典內的字典。

+0

目前還不清楚你想用簡單的字符串做什麼。例如,如果'x ['name'] =='test1''和'y ['name'] =='test2'',你想成爲什麼樣的結果? 'test1','test2'或'test1test2'?或者,就此而言,使用整數/浮點數。 –

+0

@PavelGurkov如果key/val是一樣的:忽略 – Onilol

+0

但是key/val在那裏不一樣。 –

回答

2

你的要求似乎有點模糊,但你可以做你想做一個什麼遞歸函數如下所示。 (要我明白你的要求的時候,你不能追加類型的字典權利或這些案件的喜歡?)

x = {'age': 23, 
    'channel': ['a'], 
    'name': 'Test', 
    'source': {'data': [1, 2], 'no': 'jj'}} 

y = {'age': 23, 
    'channel': ['c'], 
    'name': 'Test', 
    'source': {'data': [3, 4], 'no': 'xyz'}} 


def deep_update(x, y): 
    for key in y.keys(): 
     if key not in x: 
      x.update({key: y[key]}) 
     elif x[key] != y[key]: 
      if isinstance(x[key], dict): 
       x.update({key: deep_update(x[key], y[key])}) 
      else: 
       x.update({key: list(set(x[key] + y[key]))}) 
    return x 


print deep_update(x, y) 

{「源」:{「數據」: '':'jjxyz'},'age':23,'name':'Test','channel':['a','c']}

+0

它仍然在列表上覆制=/ – Onilol

+0

@Onilol它不會附加兩個列表同樣的,是不是你的要求? x = {'source':{'data':[3,4]}},y = {'source':{'data':[3,4]}會產生{'source':{'data': [3,4]}},不重複。 – SpiXel

+0

https://repl.it/DdFZ請檢查鏈接請 – Onilol

0

您可以訪問相關的關鍵字的值並進行更改。 讓我們已經採取了你的問題的字典例如:

x = {'name': 'Test', 'age': 23, 'channel': ['a'], 'source': {'data': [1,2]}} 
x['channel']=['a'] 

值是類型列表的[]。 可以追加或list.append()

所以添加值的列表,x['channel'].append('c')會給你:

{'age': 23, 'channel': ['a', 'c'], 'name': 'Test', 'source': {'data': [1, 2]}} 
+0

「source」呢? – Onilol

+0

只是第一種情況的延伸: –

+0

x ['source'] ['data']。append() –