You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python遍历JSON文件中的用户并输出每个用户的secret值?

遍历所有用户并输出secret值的实现方法

你可以通过遍历users字典的键值对来实现需求,以下是两种常用的简洁写法:

方法1:直接遍历键值对(直观清晰)

利用字典的items()方法同时获取用户名和对应的用户信息,直接提取secret值:

import json

with open('users_sample.json') as f:
    users = json.load(f)

# 循环遍历每个用户的键值对
for username, user_details in users.items():
    print(f"用户 {username} 的secret: {user_details['secret']}")

方法2:遍历用户名再取值(写法简洁)

先遍历字典的键(即用户名),再通过键索引到对应的secret值:

import json

with open('users_sample.json') as f:
    users = json.load(f)

for username in users:
    print(f"{username}: {users[username]['secret']}")

额外提示

with语句会自动处理文件的关闭操作,你原代码里的# f.close()注释可以直接删除,无需手动调用close()方法。

内容的提问来源于stack exchange,提问作者R2Bleep2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:57:32