How can I get a value only if it exist else return an empty dict in one line?

Question:

How to I check if a value exist and then return it and if it doesnt, return an empty dict {} (or any other operation) in one line?

I currently do the following which is will crash on none existing value + I also feel it could be written in a much more python way:

if (test[0].value):
   value = test[0].value
else
   value = {}
Asked By: PloniStacker

||

Answers:

If you have no guarantee that test, .value, or index 0 ([0]) exists:

# Try and ask for forgiveness
try:
    value = test[0].value
except (NameError, IndexError, AttributeError):
    value = {}

If you know that test[0].value exists, but want to check if it is Falsey:

Use the or operator:

value = test[0].value or {}

Or if some conditional logic is needed, you can use a ternary conditional/statement:

value = test[0].value if test[0].value else {}
Answered By: Xiddoc

You can use a try/except block:

try:
    value = test[0].value
except KeyError:
    value = {}

or .get():

value = test.get(0, {}).value

in .get(), the second parameter is what to return if the item isn’t in the dictionary.

Answered By: Pythoneer

From your question I assume that test is defined and is non-empty sequence, so that test[0] raises no errors (see other answers for those cases).

Use getattr with default:

value = getattr(test[0], 'value', {})

Demonstration

>>> import types
>>> a = types.SimpleNamespace() # so that we can add attributes
>>> getattr(a, 'value', {})
{}
# now let's add `value`
>>> a.value = 0
>>> getattr(a, 'value', {})
0
Answered By: Klas Š.

You could check if:

  • test exists in locals() or globals()
  • the index exists: -len(test) <= 0 < len(test) under the condition 0 is an int.
  • the class has the value property: getattr(test[0], 'value', None)

Then you use test[0].value.
Else you use {}

class NoData:
    pass
class Data:
    def __init__(self, value):
        self.value =value

value = test[0].value if ("test" in locals() or "test" in globals()) and -len(test) <= 0 < len(test) and getattr(test[0], 'value', None) else {}
print("NameError", value)
test = []
value = test[0].value if ("test" in locals() or "test" in globals()) and -len(test) <= 0 < len(test) and getattr(test[0], 'value', None) else {}
print("IndexError", value)
test = [NoData()]
value = test[0].value if ("test" in locals() or "test" in globals()) and -len(test) <= 0 < len(test) and getattr(test[0], 'value', None) else {}
print("AttributeError", value)
test = [Data({"a": 1})]
value = test[0].value if ("test" in locals() or "test" in globals()) and -len(test) <= 0 < len(test) and getattr(test[0], 'value', None) else {}
print("NoError", value)

Output:

NameError {}
IndexError {}
AttributeError {}
NoError {'a': 1}
Answered By: Nineteendo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.