簡體   English   中英

使用字典值循環瀏覽字典中的列表

[英]Loop through list in dictionary with dictionary values

給這樣的字典

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    

如果要“ 循環遍歷列表中的每個字典,以使用if語句比較它們​​之間的id ,則這是一種方法。 下面的if語句示例:

for i in grouped_data["results"]:
    if i['id'] > 101:
        print (i)

輸出:

{'id': 102, 'name': 'cool'}

BTW:你必須轉換totocoolstring ,除非它們是variables ,你在你的代碼已經宣布了。

不確定“用if語句比較它們​​之間的ID”是什么意思。 解釋它的方法有很多,但是您可以使用以下方法:

print (x for x in grouped_data['results'] if x['id'] > 101).next()

輸出:

{'id': 102, 'name': 'cool'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM