'Python Dict, If value is nothing, set variable to None
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
Solution 1:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | theherk |
