【问题标题】:Key Error Running Python Script (Using Atom)运行 Python 脚本的关键错误(使用 Atom)
【发布时间】:2020-07-25 15:04:33
【问题描述】:

我以前从未使用过python。我正在关注short guide on how to use an API with Python。我正在使用 Atom 文本编辑器加上 Hydrogen module 来运行上述代码。

当我运行以下段时,我得到 KeyError: '203'。

champ_dict = {}
for key in static_champ_list['data']:
        row = static_champ_list['data'][key]
    champ_dict[row['key']] = row['id']
for row in participants:
        print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])
    row['championName'] = champ_dict[str(row['champion'])]

    # print dataframe
df = pd.DataFrame(participants)
df

错误发生在下面一行

     print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])

我知道这是查找错误,但我不知道如何解决它。

这是我的代码的完整版本

    #Test Script for interacting with
    #RIOT API

#Built from 'Towards Data Science' guide

#If you want to use Hydrogen, install
#the Hydrogen Package and run
# python3 -m pip install ipykernel
# python3 -m ipykernel install --user
#This might allow pandas, idk

#-------------------------------------------

    #Get installed module for Python
import riotwatcher

    #Import tools.
from riotwatcher import LolWatcher, ApiError

    #Import pandas
import pandas as pd

    # Global variables
# Get new API from
# https://developer.riotgames.com/
api_key = 'RGAPI-XXXX-XXXX-XXXX-XXXX-XXXXXXXXXX'
watcher = LolWatcher(api_key)
my_region = 'euw1'

    #Use 'watcher' to get basic stats
me = watcher.summoner.by_name(my_region, 'RGE lnspired')
print(me)

    #Use 'watcher' to get ranked ranked stats
my_ranked_stats = watcher.league.by_summoner(my_region, me['id'])
print(my_ranked_stats)




    # Setup retrieval of match info
my_matches = watcher.match.matchlist_by_account(my_region, me['accountId'])

    # Fetch info about last match
last_match = my_matches['matches'][0]
match_detail = watcher.match.by_id(my_region, last_match['gameId'])

    #Setup Data Frame to view some of this stuff
participants = []
for row in match_detail['participants']:
        participants_row = {}
        participants_row['champion'] = row['championId']
        participants_row['spell1'] = row['spell1Id']
        participants_row['spell2'] = row['spell2Id']
        participants_row['win'] = row['stats']['win']
        participants_row['kills'] = row['stats']['kills']
        participants_row['deaths'] = row['stats']['deaths']
        participants_row['assists'] = row['stats']['assists']
        participants_row['totalDamageDealt'] = row['stats']['totalDamageDealt']
        participants_row['goldEarned'] = row['stats']['goldEarned']
        participants_row['champLevel'] = row['stats']['champLevel']
        participants_row['totalMinionsKilled'] = row['stats']['totalMinionsKilled']
        participants_row['item0'] = row['stats']['item0']
        participants_row['item1'] = row['stats']['item1']
        participants.append(participants_row)
df = pd.DataFrame(participants)
df



#So now we can look at what is referred
#to as 'Static Data'

    # check league's latest version
latest = watcher.data_dragon.versions_for_region(my_region)['n']['champion']
    # Lets get some champions static information
static_champ_list = watcher.data_dragon.champions(latest, False, 'en_US')

    # champ static list data to dict for looking up
champ_dict = {}
for key in static_champ_list['data']:
        row = static_champ_list['data'][key]
    champ_dict[row['key']] = row['id']
for row in participants:
        print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])
    row['championName'] = champ_dict[str(row['champion'])]

    # print dataframe
df = pd.DataFrame(participants)
df

【问题讨论】:

  • 这意味着键 '203' 不是字典 champ_dict 的有效键。您可以通过打印出champ_dict.keys() 来查看所有密钥
  • 谢谢@vlovero,一个命令让我的生活轻松多了。我知道这是一个简单的问题,但如果你只是发布它,我很乐意将其标记为正确。

标签: python api atom-editor keyerror riot-games-api


【解决方案1】:

为了在 python 中使用键从标准字典中检索值,它必须是有效的,否则将引发 KeyError。因此,您的代码试图将密钥 '203' 与字典 champ_dict 一起使用,但是 '203' 不是有效密钥(因此是 KeyError)。要查看字典中当前存在哪些键,您可以在 champ_dict 上调用 dict.keys 方法。示例类似于

>>> champ_dict = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
>>> champ_dict.keys()
dict_keys(['key1', 'key2', 'key3'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2021-02-20
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2016-08-11
    相关资源
    最近更新 更多