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
-
Does this answer your question? Python dictionary with default keyAziz– Aziz2022年01月26日 15:55:13 +00:00Commented 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.s3dev– s3dev2022年01月26日 15:56:14 +00:00Commented Jan 26, 2022 at 15:56
-
1Before asking a question do a bit of research on your own, it will do you goodashishpm– ashishpm2022年01月26日 15:57:41 +00:00Commented Jan 26, 2022 at 15:57
-
Does this answer your question? Dictionaries and default valuess3dev– s3dev2022年01月26日 15:58:23 +00:00Commented Jan 26, 2022 at 15:58
-
1"will return a NoneType error" A what now? Since when is NoneType an error?Kelly Bundy– Kelly Bundy2022年01月26日 16:04:28 +00:00Commented Jan 26, 2022 at 16:04
1 Answer 1
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