I’m receiving a JSON response from my server where several of the keys may or may not exist. I’ve mostly been using a bunch of ternary operators to test each key before passing them into a Django object.create method. Here’s something along the lines of what I’m dealing with
incoming = {"name":"hackNightly", "age":25, "field":"web development"}
# here's where it gets nasty
name = incoming["name"] if "name" in incoming else None
age = incoming["age"] if "age" in incoming else None
user = User.objects.create(
name = name,
age = age
)
etc. Of course, this works fine, it just feels like I’m doing something wrong. Is there a more pythonistic way to accomplish this? Thank you.
Dictionaries have a
.get()method which can be called with 1 argument (what you’re looking up), or 2 arguments (what you’re looking up, and a default value if not found). By default, using 1 argument, get will just return None if nothing is found, so you can leave it as is.