0

I'm querying an activity log via API that returns a dict. Each activity has 50 or more keys/properties. I only want to print the handful of properties that are relevant to me. Not every property I'm trying to print, like deviceIP, is always populated. If it's not populated, I want to print an empty string in place of the variable.

Is there an inline/simple way to print a default value? Something like: print(activity['deviceIP'] or "")

James
  • 5
  • 1
  • 1
    Note, this isn't an issue of a *variable being defined*, but of whether or not a *key exists in a dictionary* – juanpa.arrivillaga Oct 21 '21 at 16:15
  • In particular, `activity['deviceIP']` is not a variable. `activity` is a variable, and `activity['deviceIP']` is an expression that attempts to retrieve a particular value from the mapping that `activity` refers to. – chepner Oct 21 '21 at 16:32

1 Answers1

3

The dictionary has a get method which returns a default value instead of raising an exception. What you want is:

print(activity.get('deviceIP', ""))
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252