-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
nonetype
  • 47
  • 10
  • Does this answer your question? [Python dictionary with default key](https://stackoverflow.com/questions/33402913/python-dictionary-with-default-key) – Aziz Jan 26 '22 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. – S3DEV Jan 26 '22 at 15:56
  • 1
    Before asking a question do a bit of research on your own, it will do you good – ashishpm Jan 26 '22 at 15:57
  • Does this answer your question? [Dictionaries and default values](https://stackoverflow.com/questions/9358983/dictionaries-and-default-values) – S3DEV Jan 26 '22 at 15:58
  • 1
    "will return a NoneType error" A what now? Since when is NoneType an error? – Kelly Bundy Jan 26 '22 at 16:04

1 Answers1

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
  • 6,954
  • 3
  • 27
  • 52
RomainL.
  • 997
  • 1
  • 10
  • 24