如何从json输出数据?

cedebl8k  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(355)

我有密码:

r = requests.get(my_url)
d = sorted(r.json().values(), key=lambda x: x['players'], reverse=True)[0:5]
``` `d` 是:

[{'gamemode': 'roleplay',
'lang': 'ru',
'maxplayers': 5000,
'name': '[RolePlay][Voice] GTA5RP.COM | DownTown | gta5rp.com/discord',
'peak': 1716,
'players': 1662,
'url': 'https://gta5rp.com/'},
{'gamemode': 'roleplay',
'lang': 'ru',
'maxplayers': 5000,
'name': '[RolePlay][Voice] GTA5RP.COM | VineWood | gta5rp.com/discord',
'peak': 1578,
'players': 1568,
'url': 'https://gta5rp.com/'},
{'gamemode': 'roleplay',
'lang': 'ru',
'maxplayers': 5000,
'name': '[RolePlay][Voice] GTA5RP.COM | Eclipse | gta5rp.com/discord',
'peak': 1489,
'players': 1459,
'url': 'https://gta5rp.com/'},
{'gamemode': 'roleplay',
'lang': 'ru',
'maxplayers': 5000,
'name': '[RolePlay][Voice] GTA5RP.COM | StrawBerry | gta5rp.com/discord',
'peak': 1397,
'players': 1389,
'url': 'https://gta5rp.com/'},
{'gamemode': 'roleplay',
'lang': 'ru',
'maxplayers': 3500,
'name': '[RolePlay][Voice] GTA5RP.COM | Sunrise | gta5rp.com/discord [1.1]',
'peak': 1337,
'players': 1323,
'url': 'https://gta5rp.com/'}]

如何使用 `for` 这样地?

print('Name: ', d["name"]... etc

cngwdvgl

cngwdvgl1#

for i in d:
    print('Name: ', i["name"])
n7taea2i

n7taea2i2#

d是一个字典列表,因此您可以在该列表上迭代以获取每个dict并格式化输出:

for data in d:
    output = f'name: {dic["name"]}, peak: {dic["peak"]}'  # etc
    print(output)

结果:

name: [RolePlay][Voice] GTA5RP.COM | DownTown | gta5rp.com/discord, peak: 1716

相关问题