如何用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
相关产品推荐
相关产品推荐

