如何将此词典中的所有ID值放入列表中?

2024-10-04 11:25:45 发布

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

基本上,我想返回这个JSON数据中的所有“ID”值,并将它们放入一个列表中:

https://www.roblox.com/games/getgameinstancesjson?placeId=70501379&startindex=0

这是我目前掌握的密码。它返回上面的所有JSON数据并将其放入字典中。问题是,我完全不知道如何进入字典并获取ID值这是个怪物。请帮忙。你知道吗

import urllib, json

url = "https://www.roblox.com/games/getgameinstancesjson?
placeId=70501379&startindex=0"

response = urllib.urlopen(url)

data = json.loads(response.read())

Tags: 数据httpscomidjsonurl字典www
3条回答

您需要遍历JSON数据结构来收集所有id。你知道吗

 import urllib, json

url = "https://www.roblox.com/games/getgameinstancesjson?placeId=70501379&startindex=0"

response = urllib.urlopen(url)

data = json.loads(response.read())
ids = []
for i in data["Collection"][0]["CurrentPlayers"]:
    ids.append(i["Id"])
print ids

所以基本上,你是在尝试累积所有当前玩家的ID。你知道吗

ids = []
for entry in data['Collection']:
    ids.extend(player['Id'] for player in entry['CurrentPlayers'])

这些当前玩家共有7个集合共享,下面是@wiludsdaman答案的显式版本

ids = []
for collection in data["Collection"]:
    for player in collection["CurrentPlayers"]:
        ids.append(player["Id"])

print ids

如果你更勇敢,你可以使用双列表理解来压缩上面的代码

ids = [player["Id"] for collection in data["Collection"] for player in collection["CurrentPlayers"]]

相关问题 更多 >