如何在json对象(Python)中获取键值

2024-06-26 13:46:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的json:

{'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

我想获得name的所有值的列表。
我的python代码应该是什么


Tags: 代码nametestjson列表uidpasswordtesting
2条回答

d.values给出所有值,然后可以获得每个值的属性name

d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

[i['name'] for i in d.values()]
['poulami', 'test']

还要注意d.values返回一个生成器,而不是一个列表,以便转换为list uselist(d.values())

这不是JSON格式。它是一个Python字典

迭代字典(d.values())的值,并从每个项中获取name

d = {'1': {'name': 'poulami', 'password': 'paul123', 'profession': 'user', 'uid': 'poulamipaul'}, '2': {'name': 'test', 'password': 'testing', 'profession': 'tester', 'uid': 'jarvistester'}}

names_list = []

for i in d.values():
    names_list.append(i['name'])
names_list = ['poulami', 'test']

相关问题 更多 >