2017-09-14 93 views
-1

我剛開始學習Django和Python ...已經2個月了。 我正在做我自己的個人項目之一,我有一個部分在哪裏查詢web服務並將結果傳遞迴模板。循環裏面的字典python

webservice正在返回一個字典,如下所示。

x = {'ID':[{ 
    'key-1': 'First Name', 
    'key-2': 'John' 
},{ 
    'key-1': 'Last Name', 
    'key-2': 'Doe' 
},{ 
    'key-1': 'Age', 
    'key-2': '25' 
}] 

我期待遍歷字典裏面的列表,並創建自己的字典,如下面:

d = {'First Name': 'John', 'Last Name': 'Doe', 'Age': '25' }

我不知道我失去了什麼,有人可以幫助我學習如何建立我的字典?

+1

你可以證明你到目前爲止已經嘗試了什麼,並談論你遇到的具體問題嗎? – pvg

+0

我試圖做某人在這裏解釋... https://stackoverflow.com/questions/18289678/python-iterating-through-a-dictionary-with-list-values 但它是不一樣的我正在查看... – ppv

+0

如果您的外部字典被命名爲'x',只需在x ['ID']中爲el執行'{el ['key-1']:el ['key-2']}' –

回答

0

買者請注意字典的values方法的排序規則。訂購規則2.x documentation3.x documentation

EDIT2:

爲了防止字典排序和提供解決方案的任何怪事,包裝你的數據到OrderedDict

from collections import OrderedDict 

x = {'ID':[OrderedDict({ 
     'key-1': 'First Name', 
     'key-2': 'John' 
     }),OrderedDict({ 
     'key-1': 'Last Name', 
     'key-2': 'Doe' 
     }),OrderedDict({ 
     'key-1': 'Age', 
     'key-2': '25' 
     })]} 

dict()是這樣的一個不錯的選擇:

d = dict(each.values() for each in x['ID']) 

輸出:

{'Age': '25', 'First Name': 'John', 'Last Name': 'Doe'} 
1

嘗試一個詞典理解和建立一個新的字典與key-1 as the key and key-2`作爲價值。

x = {'ID':[{ 
    'key-1': 'First Name', 
    'key-2': 'John' 
},{ 
    'key-1': 'Last Name', 
    'key-2': 'Doe' 
},{ 
    'key-1': 'Age', 
    'key-2': '25' 
}]} 


print({el['key-1']: el['key-2'] for el in x['ID']}) 

結果

{ '年齡': '25', '名': '約翰', '姓': '李四'}