2016-01-05 54 views
-2

我有以下的python的dicts列表。合併dict的列表爲python的一個字典

[ 
{ 
"US": { 
"Intial0": 12.515 
}, 
{ 
"GE": { 
"Intial0": 11.861 
} 
}, 
{ 
"US": { 
"Final0": 81.159 
} 
}, 
{ 
"GE": { 
"Final0": 12.9835 
} 
} 
] 

我想作爲

[{"US": {"Initial0":12.515, "Final0": 81.159}}, {"GE": {"Initial0": 11.861, "Final0": 12.9835}}] 

我這個從相當長的一段時間掙扎類型的字典的最終名單。任何幫助?

+0

爲什麼你想要的,而不是一個單一的字典? '{「US」:{...},「GE」:{...}}? –

+0

相關[如何合併多個同一個鍵的字典?](http://stackoverflow.com/questions/5946236/how-to-merge-multiple-dicts-with-same-key) – fredtantini

+2

Rohit,你有什麼嘗試?你看過使用更新嗎? http://www.tutorialspoint.com/python/dictionary_update.htm –

回答

1

你可以使用Python的defaultdict如下:

from collections import defaultdict 

lod = [ 
    {"US": {"Intial0": 12.515}}, 
    {"GE": {"Intial0": 11.861}}, 
    {"US": {"Final0": 81.159}}, 
    {"GE": {"Final0": 12.9835}}] 

output = defaultdict(dict) 

for d in lod: 
    output[d.keys()[0]].update(d.values()[0]) 

print output 

對於給定的數據,這將顯示如下:

defaultdict(<type 'dict'>, {'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}}) 

或者你可以將其與print dict(output)轉換回標準的Python字典給出:

{'GE': {'Intial0': 11.861, 'Final0': 12.9835}, 'US': {'Intial0': 12.515, 'Final0': 81.159}} 
0

list1 = [{「US」:{「Intial0」:12。 {「GE」:{「Intial0」:11.861}},{「US」:{「Final0」:81.159}},{「GE」:{「Final0」:12.9835}}]

dict_US = {} dict_GE = {} 用於list1的dict_x: 如果dict_x.keys()== [ 'US']: dict_US.update(dict_x [ 「美國」]) 如果dict_x.keys()= = [ 'GE']: dict_GE.update(dict_x [ 「GE」]) 列表2 = [{ 「US」:dict_US},{ 「GE」:dict_GE}] 打印列表2

相關問題