-2

I've made a program that fetches data from an api and then uses some keys of it. It should return the keys, but if a certain key has no value- or is not in the data I want it to return that key with a 0.

So for example when looking up a certain player's karma (karma = r.json()["player"]["karma"]) It will return a NoneType error as the value is empty. How can I make it set that value to 0, without writing a dozen for loops checking each one individually?

What I don't want (as there are a lot of keys):

try:
 karma = r.json()["player"]["karma"]
except NoneType:
 karma = 0
asked Jan 26, 2022 at 15:51
5
  • Does this answer your question? Python dictionary with default key Commented Jan 26, 2022 at 15:55
  • Did you try a quick internet search, before posting this elementary question? A bit of work on your part would have quickly uncovered the answer. Please leave SO questions as a last resort after you have tried to find the answer on your own. Commented Jan 26, 2022 at 15:56
  • 1
    Before asking a question do a bit of research on your own, it will do you good Commented Jan 26, 2022 at 15:57
  • Does this answer your question? Dictionaries and default values Commented Jan 26, 2022 at 15:58
  • 1
    "will return a NoneType error" A what now? Since when is NoneType an error? Commented Jan 26, 2022 at 16:04

1 Answer 1

3

Well you just discover the get method.

karma = r.json()["player"].get("karma", 0)

The first argument is the key you want the value. The second argument is the default value to return if the key does not exist, by default its value is None

theherk
7,6183 gold badges32 silver badges62 bronze badges
answered Jan 26, 2022 at 15:53
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.