Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1 liner 'pythonic' code that returns a set rather than a list

I would like to do the following code, except in a neat 1-liner:

terms_set = set([])
for term in terms: 
    if index.has_key(term): 
        terms_set.add(index[term])

Is it possible to do? Must return a set.

like image 525
Craig Avatar asked Dec 15 '22 17:12

Craig


2 Answers

You can use a set comprehension:

terms_set = {index[term] for term in terms if term in index}

Note that key in dict is preferred over dict.has_key, which was deprecated in Python 2 and is not available in Python 3.

like image 194
lvc Avatar answered Feb 19 '23 15:02

lvc


terms_set = set(index[term] for term in terms if index.has_key(term))
like image 30
Travis Griggs Avatar answered Feb 19 '23 15:02

Travis Griggs