0

Please I need help, I have to check if some values exist in dictionary so I have multiple try except statements. So, what I'm thinking is to write a function that takes the dict and checks if that value exist or not (if it didn't exist will return None) but the problem is when I call that function with dict as parameter it gives error since that field doesn;t exits. So here is what I did so far but is giving error in main function:

def main():
  return_value = test(dict["one"]["two"])

And here is the test function:

def test(value):
  try:
    one = value
  except:
    one = None
  finally:
    return one
HElooo
  • 13
  • 3
  • The problem is you aren't passing a dictionary to your function. You *doing `dict["one"]["two"]`* which gets *evaluated first*, and the result of that is actually passed to your function. Since `dict["one"]["two"]` throws an error, your function is never actually invoked. And note, `one = value` would never throw an error anyway. You have a fundamental misconception of how Python evaluates arguments. Some languages actually work how you assumed it would, that evaluation strategy is "call by name", but Python doesn't use that – juanpa.arrivillaga Oct 07 '20 at 10:10

2 Answers2

1

If you want to test if a value exists as a key in a dictionary , simply do this:

value in dict

Example:

d = { 4 : "exists"}

assert 4 in d
assert 5 not in d

If you want a default value, you can use get:

v = d.get(5, "mydefault")
assert v == "mydefault"
Christian Sloper
  • 6,238
  • 2
  • 11
  • 28
1

You can use the method get() from dict. It will return None if your dict does not have the key.

return_value = dict.get("one")
# return_value is equal to None if "one" is not in the dict
Karl Knechtel
  • 51,161
  • 7
  • 77
  • 117
Krophil
  • 21
  • 5
  • How I can change that if I want to check not just the key "one" l want to check ["one"]["two"] is in dict? – HElooo Oct 07 '20 at 09:55
  • You can see answers to this problem here : https://stackoverflow.com/questions/28225552/is-there-a-recursive-version-of-the-dict-get-built-in – Krophil Oct 07 '20 at 10:00
  • ohh thanks that is exactly what I'm looking for, thank you agian :) – HElooo Oct 07 '20 at 10:10