2016-03-03 114 views
-4

我的字典[{'abc':10,'efg':20,'def':30},{'abc':40,'xya':20,'def':50}]的名單,我想在創建一個數組abc[]並存儲相應的值array.so輸出應該看起來像迭代數組

abc[10,40] 
def[30,50] 
efg[20] 

等字典和儲值上,使用python。

+0

所以你想得到的數組的名稱是字典的關鍵。正確? – zaxliu

+5

到目前爲止,您嘗試過哪些方法?嘗試實施解決方案時遇到了哪些問題? –

+0

歡迎來到StackOverflow。請閱讀並遵守幫助文檔中的發佈準則。 [最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve)適用於此處。在您發佈代碼並準確描述問題之前,我們無法有效幫助您。 StackOverflow不是一個編碼或教程服務。 – Prune

回答

0

任何確切的解決方案可能會涉及到的exec()或東西的陌生人,最Python程序員可能會鼓勵你,而不是改變你的詞典列表插入列表的詞典:

from collections import defaultdict 

list_of_dictionaries = [ 
    {'abc':10,'efg':20,'def':30}, 
    {'abc':40,'xya':20,'def':50}, 
] 

dictionary_of_lists = defaultdict(list) 

# there's probably some clever one liner to do this but let's keep 
# it simple and clear what's going when we make the transfer: 

for dictionary in list_of_dictionaries: 
    for key, value in dictionary.items(): 
     dictionary_of_lists[key].append(value) 

# We've achieved the goal, now just dump dictionary_of_lists to prove it: 

for key, value in dictionary_of_lists.items(): 
    print(key, value) 

,輸出:

xya [20] 
def [30, 50] 
abc [10, 40] 
efg [20] 

不完全是你要求的,但應該是,爲了大多數目的,你需要什麼。