簡體   English   中英

如何遍歷 python 中的嵌套列表?

[英]How to iterate through a nested list in python?

我想遍歷一個里面有很多字典的列表。 我試圖迭代的 json 響應看起來像這樣:

user 1 JSON response:
[
 {
 "id": "333",
 "name": "hello"
 },
 {
 "id": "999",
 "name": "hi"
 },
 {
 "id": "666",
 "name": "abc"
 },
]

user 2 JSON response:
[
 {
 "id": "555",
 "name": "hello"
 },
 {
 "id": "1001",
 "name": "hi"
 },
 {
 "id": "26236",
 "name": "abc"
 },
]

這不是實際的 JSON 響應,但其結構相同。 我想要做的是找到一個特定的id並將其存儲在一個變量中。 我試圖迭代的 JSON 響應沒有組織,並且每次都根據用戶而變化。 所以我需要找到特定的id ,這很容易,但列表中有很多字典。 我試過這樣迭代:

    for guild_info in guilds:
        for guild_ids in guild_info: 

這將返回第一個字典,它是 id: 333。例如,我想找到值 666 並將其存儲在一個變量中。 我該怎么做?

你有一個字典列表。

當您在for guild_info in guilds:您將遍歷字典,因此這里每個guild_info都將是一個字典。 因此,只需像這樣獲取密鑰idguild_info['id']

如果您要做的是找到與特定id對應的name ,則可以使用列表推導並獲取其第一個元素,如下所示:

name = [x['name'] for x in guilds if x['id'] == '666'][0]

這是一個 function,它只會搜索直到找到匹配的id然后返回,這樣可以避免不必要地檢查更多條目。

def get_name_for_id(user, id_to_find):
    # user is a list, and each guild in it is a dictionary.
    for guild in user:
        if guild['id'] == id_to_find:
            # Once the matching id is found, we're done.
            return guild['name']

    # If the loop completes without returning, then there was no match.
    return None

user = [
    {
        "id": "333",
        "name": "hello"
    },
    {
        "id": "999",
        "name": "hi"
    },
    {
        "id": "666",
        "name": "abc"
    },
]

name = get_name_for_id(user, '666')
print(name)
name2 = get_name_for_id(user, '10000')
print(name2)

Output:

abc
None

這將創建一個循環,該循環將迭代到字典列表。如果您正在尋找簡單的方法

for every_dictionary in List_of_dictionary:
    for every_dictionary_item in every_dictionary.keys():
        print(every_dictionary[every_dictionary_item])

暫無
暫無

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

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