python - 如何遍历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 并将其存储在一个变量中。我该怎么做?
解决方案
这是一个只搜索直到找到匹配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
推荐阅读
- ms-access - 具有唯一验证器的随机字母数字生成器在发现唯一冲突时返回额外数字
- logic - 基于逻辑的灯光系统
- sas - SAS 访问宏变量名
- r - 按组填写日期的缺失行
- c# - 片段管理器空引用异常
- python - 安装 jupyter 主题后,笔记本和 docker 容器不再工作
- shell - 在 shell 命令中删除和替换文件
- azure - powerBI azure 客户端应用程序对其他应用程序的权限以进行报表嵌入
- iterm2 - 以编程方式清除 iterm2 缓冲区
- spring-boot - Spring CLI 问题 - 无法在 CLI 中列出 Spring Cloud 服务