2017-03-03 355 views
-4

我想合併兩個我有的列表。將兩個字典合併爲一個結果字典

gpbdict = dict(zip(namesb, GPB)) 
>>> {'1': True, '3': True, '2': True, '5': True, '4': True, '7': True, '6': True, '8': True} 
gpadict = dict(zip(namesa, GPA)) 
>>> {'11': True, '10': True, '13': True, '12': True, '15': True, '14': True, '16': True, '9': True} 

但是,它似乎並不簡單到只是:

json.loads(gpadict + gpbdict) 

gpa_gpb = [gpadict, gpbdict] 
print json.dumps(gpa_gpb, indent=2, sort_keys=True)) 
只是稍後

會產生一個結果有兩個單獨的列表:

>>>[ 
>>> { 
>>> "10": true, 
>>> "11": true, 
>>> "12": true, 
>>> "13": true, 
>>> "14": true, 
>>> "15": true, 
>>> "16": true, 
>>> "9": true 
>>> }, 
>>> { 
>>> "1": true, 
>>> "2": true, 
>>> "3": true, 
>>> "4": true, 
>>> "5": true, 
>>> "6": true, 
>>> "7": true, 
>>> "8": true 
>>> } 
>>>] 

有沒有我失蹤的一步?

+2

[如何在單個表達式中合併兩個Python字典?](http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-表情) – mkrieger1

+0

你可以通過谷歌輕鬆找到這個問題的答案。 Veeeeery容易。你也應該學習更多關於Python術語的知識。 –

+0

@anandtripathi小心!字典上的'update'方法不*返回任何東西。但是你評論的本質是真實有效的。 – MariusSiuram

回答

3

你正在做一些奇怪的事情。

首先,你想合併Python對象,不是嗎?爲什麼以及如何? gpbdictgpbadict都是字典(不是list),所以你的問題不是很具體。預計json.loads會收到一個字符串(一個JSON)而不是一個Python對象。所以,也許你只是想:

gpbadict = dict(zip(namesb + namesa, GPB + GPA)) 

注意+工程確定與名單,但不使用詞典的運營商。

如果要合併的詞典,在另一方面,你可以使用update

gpadict.update(gpbdict) 

這將有效地合併詞典:gpadict將成爲雙方gpadict(起始之一)的組合和gpbdict。如果有重複的密鑰,它們將被覆蓋。

而在整個問題中,我找不到任何真正的JSON參考。我錯過了什麼?