Check index in Dict

Asked

Viewed 138 times

2

I have a function that returns me 2 results, None or dict however I am trying to verify 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 a comparison attempt using a if inline:

a = x if 'my_key' in result else None

On my computer I can accomplish this task even with None but me my notebook no, this has to do with the python version? and how can I solve this?

Python 3.5.2

  • What’s the operation you’re trying to do next? when you make that mistake?

  • @Miguel I take the result and try to make a comparison with the if inline, a = x if 'my_key' in result else None

1 answer

2


In the comparison check 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
  • I get the same error because the comparison result is not None cannot be eternal.

  • I’m gonna fix @Rafaelacioly

  • I made no iteration after this if

  • This error is given to you inside the function you put in your c+Odigo? @Rafaelacioly

  • No, the error is given outside the function, so when I perform the comparison with the if

  • I already know why it is... I’ll put in the reply @Rafaelacioly

  • The last code you put is exactly what I posted in the question, and it doesn’t work.

  • @Rafaelacioly you have to make your function return an empty Dict instead of None, I explained over the code

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.