kami
kami

Reputation: 13

.get() python json file discord bot

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?

Upvotes: 1

Views: 351

Answers (2)

WillMonge
WillMonge

Reputation: 1035

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.

Upvotes: 1

William Mak
William Mak

Reputation: 1

So right off the back your friend was probably referring to the fact you could do something like this: lb = list(map(lambda m: (m, users.get(m.id, {'xp': 0}).get('xp')), message.server.members)]

But as to why this works, you should first read the documentation: https://docs.python.org/2/library/stdtypes.html#dict.get

But I think you might prefer a list comprehension for what you're doing instead: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

for example you could rewrite how you get your lb variable like so:

lb = [(member, users[member.id].get('xp')) for member in message.server.members if member.id in users]

This is equivalent to writing the following:

lb = []
for member in message.server.members:
    # Check if the member is in your users list
    if member.id in users: 
        lb.append((member, users[member.id].get('xp')))

Upvotes: 0

Related Questions