当然必须有一个更清洁的方法来做到这一点

Dan*_*iel 0 python arrays json dictionary

我正在构建一个可以显示一些统计数据的机器人.

我从API获得此响应:

"lifeTimeStats": [
{
  "key": "Top 5s",
  "value": "51"
},
{
  "key": "Top 3s",
  "value": "69"
},
{
  "key": "Top 6s",
  "value": "120"
},
{
  "key": "Top 10",
  "value": "66"
},
{
  "key": "Top 12s",
  "value": "122"
},
{
  "key": "Top 25s",
  "value": "161"
},
{
  "key": "Score",
  "value": "235,568"
},
{
  "key": "Matches Played",
  "value": "1206"
},
{
  "key": "Wins",
  "value": "49"
},
{
  "key": "Win%",
  "value": "4%"
},
{
  "key": "Kills",
  "value": "1293"
},
{
  "key": "K/d",
  "value": "1.12"
}
],
Run Code Online (Sandbox Code Playgroud)

这是我的格式化这个JSON的代码:

def __getitem__(self, items):
    new_list = []
    new_list2 = []
    new_list3 = []
    new_list4 = []

    for item in self.response['lifeTimeStats']:
        for obj in item.items():
            for object in obj:
                new_list.append(object)

    for item in new_list[1::2]:
        new_list2.append(item)

    for item in new_list2[::2]:
        new_list3.append(item)

    for item in new_list2[1::2]:
        new_list4.append(item)

    result = dict(zip(new_list3, new_list4))

    return result[items]
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

{
'Top 5s': '1793',
'Top 3s': '1230',
'Top 6s': '1443',
'Top 10': '2075',
'Top 12s': '2116',
'Top 25s': '2454',
'Score': '4,198,425',
'Matches Played': '10951',
'Wins': '4077',
'Win%': '37%',
'Kills': '78836',
'K/d': '11.47'
}
Run Code Online (Sandbox Code Playgroud)

我对结果感到满意,而我只是在思考是否有更好的格式化方法?更干净的方式?

我正在学习,我会检查是否有人对此有所了解.

这是我在此之后获取信息的方式:

f = Fortnite('PlayerName')
f['Matches Played']
Run Code Online (Sandbox Code Playgroud)

zwe*_*wer 5

您可以使用简单的dict理解来迭代结果,即:

def __getitem__(self, item):
    return {x["key"]: x["value"] for x in self.response["lifeTimeStats"]}[item]
Run Code Online (Sandbox Code Playgroud)

话虽如此,为什么每当你想要检索特定项目时,你会一直迭代响应?您应该缓存结果,然后只需将其作为普通字典访问.

或者,因为您只对一个键感兴趣,所以您可以这样做:

def __getitem__(self, item):
    for stat in self.response["lifeTimeStats"]:
        if stat["key"] == item:
            return stat["value"]
Run Code Online (Sandbox Code Playgroud)