Reputation: 843
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.
Upvotes: 4
Views: 98
Reputation: 156228
So it looks like you want term_set
to contain all of the values in index
(some dict), so long as its' key is also mentioned in terms
(some iterable). regarding both as sets, that's intersection, which is roughly, for the keys at least, set(terms) & set(index)
, but that generates two sets, and we're actually interested in neither (we want values, not keys). We can elide one of them with set(terms).intersection(index)
(or visa versa, depending on which one is larger (we want the smaller on the left).
We can use our good friend map
to get the values.
how about this?
term_set = map(index.get, set(terms).intersection(index))
or even:
term_set = map(index.get, index.keys() & terms)
(in python2.7, you would need index.viewkeys()
)
Hmm... thinking about it, dict.get
can return a default value (ie None
), which we could strip out after-the fact (if it occured)
term_set = set(map(index.get, terms))
term_set.discard(None)
which construts NO intermediate collections (assuming python3, otherwise map should be itertools.imap
)
Although if None
can occur as a value in index, you'd end up having to do something tedious like:
sentinel = object()
term_set = {index.get(term, sentinel) for term in terms} - {sentinel}
which is not at all better than the accepted answer.
Upvotes: 2
Reputation: 35089
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.
Upvotes: 7
Reputation: 22697
terms_set = set([index[term] for term in terms if index.has_key(term)])
Upvotes: 0
Reputation: 22252
terms_set = set(index[term] for term in terms if index.has_key(term))
Upvotes: 2
Reputation: 214979
This?
set(index[t] for t in terms if t in index)
Note that has_key
is deprecated, use key in dict
instead.
Upvotes: 1