Search code examples
pythondictionaryiterationlist-comprehension

Using next instead of break in comprehension list


Considering a word, I'd like to search it in a dictionary, first as key and then as value.

I implemented in the following way:

substitution_dict={'land':['build','construct','land'],
                   'develop':['develop', 'builder','land']}
word='land'
key = ''.join([next(key for key, value in substitution_dict.items() if word == key or word in value)])

The idea is to take advantage of short-circuiting, the word is first compare with the key, else with the value. However, I'd like to stop when is found in the key.

Running the above snippet works good. However, when the word changes to other word not present in the dictionary, it throws StopIteration error due to the next statement which is not finding results.

I was wondering if this is doable in one line as I intended.

Thanks


Solution

  • You could pass a default argument in next().And next() would only return only one element,so "".join([]) is unnecessary.

    Code below:

    key = next((key for key, value in substitution_dict.items() if word == key or word in value), None)
    

    When the iterator is exhausted, it would return None.

    Or if you really want to use it with ''.join, like:

    key = "".join([next((key for key, value in substitution_dict.items() if word == key or word in value), "")])