[英]How to Iterate over JSON object or dictionary
I'm new to Python and I'm having trouble with a Json object. 我是Python的新手,并且在使用Json对象时遇到麻烦。 What would be the best way to do this iteration?
进行此迭代的最佳方法是什么? I need to collect the Rank of all users)
我需要收集所有用户的排名)
//JSON file // JSON文件
"total": 2702,
"pageIndex": 1,
"pageSize": 100,
"data": [
{
"rank": 1,
"handle": "saarixx",
"color": "Red",
"rating": 3249,
"highestRatingType": "Design"
},
{
"rank": 2,
"handle": "kyky",
"color": "Red",
"rating": 2785,
"highestRatingType": "Design"
},
{
"rank": 3,
"handle": "dmks",
"color": "Red",
"rating": 2575,
"highestRatingType": "Design"
},
//What I tried //我尝试了什么
response = requests.get("https://api.topcoder.com/v2/users/tops/develop/", params=pages)
data = json.loads(response.text)
for i in data.items():
print(data['data'][i]['rank'])
Use a simple list
comprehension: 使用简单的
list
理解:
[user['rank'] for user in data['data']]
Output: 输出:
[1, 2, 3]
A couple of different ways to do this, loop, list comprehension or my new favorite (and probably overkill) Pandas DataFrame. 有两种不同的方法可以执行此操作:循环,列表理解或我最喜欢的(可能是过大的)Pandas DataFrame。
import requests
import pandas as pd
response = requests.get("https://api.topcoder.com/v2/users/tops/develop/")
data = response.json()
player_stats = data['data']
player_stats_df = pd.DataFrame(player_stats)
player_stats_df
The above code generates a nice structured table. 上面的代码生成了一个漂亮的结构化表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.