I have a json file that stores the ids, xp and level of who writes on my server. I'm making a leaderboard to show the people who have most xp on my server, however a keyerror appears: KeyError: '370034734186758173'
Could someone help me fixing this error?
The .get
would be used when accessing the users
dictionary. You can add a second parameter to the call as the default (in case you don't find such a key), which in the first call you should output a empty dictionary, so that the second .get
doesn't fail.
lb = list(map(lambda m: (m, users.get(m.id, {}).get("xp"), message.server.members))
Since you are making a list out of it, you may also want to try (the somewhat more pythonic) list comprehension (not that your line has anything wrong with it):
lb = [ (m, users.get(m.id, {}).get("xp") for m in message.server.members ]
Note that both approaches will return a None item when the get doesn't find the Key in the dictionary, you can ommit this using an if
clause in the list comprehension:
lb = [ (m, users.get(m.id, {}).get("xp") for m in message.server.members if m.id in users ]
As a side note, I would add that you have included everything within the context manager clause (with open():
), while only the line where you load its contents is necessary. It would be best practice to de-indent the rest of your code.