Check index in dict

2

I have a function that returns 2 results, None or dict however I am trying to check if a key specifies this in the result of this function.

def get_language(card):
if not card.foreign_names == None:
    for c in card.foreign_names:
        if c['language'].lower().startswith('Portuguese'.lower()):
            return c
return None

When the function returns a dict I can easily check the key as follows:

result = get_language(card)
'my_key' in result

But if the function returns None I get the following error:

  

TypeError: argument of type 'NoneType' is not iterable

This error is generated due to an attempt to compare using% inline%:

a = x if 'my_key' in result else None

On my computer I can perform this task even with if but I do not have my notebook, does this have to do with the python version? and how can I resolve this?

  

Python 3.5.2

    
asked by anonymous 21.01.2017 / 13:17

1 answer

2

In the comparison it checks first if result is None, and only then if the key exists:

result = None
a = result['my_key'] if result is not None and 'my_key' in result else None
print(a) # None

...

result = {'my_key': 123}
a = result['my_key'] if result is not None and 'my_key' in result else None
print(a) # 123

You could also easily remedy and maintain the condition as you have it, if instead of None your function returns an empty dictionary, return {} :

result = {}
a = result['my_key'] if 'my_key' in result else None
print(a) # None
    
21.01.2017 / 13:28