简体   繁体   中英

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

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), "")])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM