0
ex1 = {'value': '1, 2, 2, 3, 2, 2, 3, 3, 4, 3, 3, 5, 5, 5, 5, 5, 5, 5', 'number': '1197916152', 'key': '44'}
ex2 = {'number': '1197916152', 'key': '2'}

I've got a dictionaries like above. I need to check if a dict contains value key, and if not, return 1. I tried with the following:

np.where('value' in ex1, ex1['value'], 1)
np.where('value' in ex2, ex2['value'], 1)

And while it works fine with ex1, it returns an error with ex2:

KeyError Traceback (most recent call last) ' in () ----> 1 np.where('value' in ex2, ex2['value'], 1)

KeyError: 'value'

It seems ex2['value'] seems to be evaluated even when a condition is not fulfilled. Am I right? And how can I adjust that?

jakes
  • 1,964
  • 3
  • 18
  • 50
  • Yes, but I was expecting that `ex2['value']` is not evaluated as condition `'value' in ex2` is not met. – jakes Mar 15 '19 at 13:15
  • The problem is `np.where` evaluates both arguments and then decides what to pick based on the condition. – cs95 Mar 15 '19 at 13:16
  • 1
    Calling `np.where`, or any other function, always evaluates all the passed arguments, and trying to evaluate `ex2['value']` fails. Use instead the native Python construct, which is ` if else ` (e.g. `ex1['value'] if 'value' in ex1 else 1`), or, in the case of dicts, you can just do `ex1.get('value', 1)`. – jdehesa Mar 15 '19 at 13:16

2 Answers2

3

For a simpler solution, use the dictionary .get method to fetch the content of the value key, and set 1 as default in case it does not exist:

ex1.get('value', 1)

ex1.get('value', 1)
# '1, 2, 2, 3, 2, 2, 3, 3, 4, 3, 3, 5, 5, 5, 5, 5, 5, 5'

ex2.get('value', 1)
# 1
yatu
  • 86,083
  • 12
  • 84
  • 139
0
np.where('value' in ex2, ex2.get('value'), 1)