首页 > 解决方案 > 如何遍历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 并将其存储在一个变量中。我该怎么做?

标签: pythonpython-3.xlist

解决方案


这是一个只搜索直到找到匹配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)

输出:

abc
None

推荐阅读