Reputation: 2911
I have the following dict:
{('I', 'like'):14, ('he','likes'):2, ('I', 'hate'):12}
For a given word
string I want to get the second element of all tuples in dictionary (which is a key of a dictionary) that has this word
as the first element.
I tried:
word='I'
second_word = (k[0][1] for k, v in d if word == k[0][0])
print(second_word)
and expected to get "like" as an answer but got:
<generator object generate_ngram_sentences.<locals>.<genexpr> at 0x7fed65bd0678>
<generator object generate_ngram_sentences.<locals>.<genexpr> at 0x7fed65bd0678>
<generator object generate_ngram_sentences.<locals>.<genexpr> at 0x7fed65bd06d0>
EDIT: 2. Can you share how could it be modified in case the size of the tuple to be dynamic. So that the key of the dict would store eg. 2elem tuple or 15elem etc. tuple depending on dict?
Upvotes: 1
Views: 3480
Reputation: 23144
I steal the first sentence from Reblochon Masque's answer:
You have the correct idea, but it needed to be fine tuned:
second_word = (k[0][1] for k, v in d if word == k[0][0])
Iterating directly over d
generates the keys only (which are what you are interested in, so this was the right idea).
Now, for k, v in d
actually works, not because you get the key and the value, but because the key is a tuple and you unpack the two items in the tuple to the names k
and v
.
So k
already is the first word and v
is the second word, and you don't need to use any indexing like [0][0]
or [0][1]
.
Using different names makes it clearer:
word = 'I'
second_words = (second for first, second in d if first == word)
Note that now second_words
is a generator expression and not a list. If you simply go on iterating over second_words
this is fine, but if you actually want the list, change the generator expression to a list comprehension by replacing the ()
by []
.
Upvotes: 2
Reputation: 36662
You have the correct idea, but it needed to be fine tuned:
d = {('I', 'like'):14, ('he','likes'):2, ('I', 'hate'):12}
word='I'
second_word = [k[1] for k in d if k[0] == 'I']
print(second_word)
The output is a list of all second words for all the lkeys whose first item is 'I'
['like', 'hate']
from there:
second_word[0] --> 'like'
Upvotes: 3