給定一個字典作爲這樣遍歷與詞典列表值
grouped_data = {"results":[{"id": 101, "name": toto}, {"id": 102, "name": cool}] }
它已經在其有字典
希望我沒有混淆你的列表的字典),如何我可以獲得結果列表並遍歷列表中的每個字典,以將它們之間的id與if語句進行比較。
給定一個字典作爲這樣遍歷與詞典列表值
grouped_data = {"results":[{"id": 101, "name": toto}, {"id": 102, "name": cool}] }
它已經在其有字典
希望我沒有混淆你的列表的字典),如何我可以獲得結果列表並遍歷列表中的每個字典,以將它們之間的id與if語句進行比較。
以獲取列表:
resultList = grouped_data["results"]
迭代列表以獲得字典:
for dic in resultList:
# use dic
內dic
要獲取值:
for dic in resultList:
for key,value in dic.iteritems():
# use key and value
要訪問id
關鍵,使用:
for dic in resultList:
if dic['id'] == somevalue:
# do_something
什麼是完全鍵和值? – MadBoy
如果你想「循環通過列表內每個字典與if語句之間的id
比較」,這是做這件事。 例if
下面的語句:
for i in grouped_data["results"]:
if i['id'] > 101:
print (i)
輸出:
{'id': 102, 'name': 'cool'}
BTW:你必須toto
和cool
轉換爲string
,除非它們是你在你的代碼都宣稱已經variables
。
不確定你的意思是'比較他們之間的id與if語句'。許多方法來解釋,但這裏的東西,你可以使用:
print (x for x in grouped_data['results'] if x['id'] > 101).next()
輸出:
{'id': 102, 'name': 'cool'}
不需要你的幫助,已經得到了它的工作多虧了真正的答案 – MadBoy