Reputation: 401
I have a dictionary where the values are tuples. The structure is something like this:
my_dictionary = {'class1': (5, 10, 15, 20), 'class2': (1, 2, 3, 4), 'class3': (10, 20, 30, 40)}
Now I want to loop over the dictionary keys and take a specific element from the tuple of values, so say I want to get the first tuple element of each class. How to do that?
Upvotes: 2
Views: 1593
Reputation: 1776
Now I want to loop over the dictionary keys and take a specific element from the tuple of values
print(*(my_dictionary[i][0] for i in my_dictionary)) #5 1 10
As asked:
Why is it so memory efficient?
Upvotes: 0
Reputation: 26315
You could also unpack the first item from each tuple in my_dictionary.values()
:
>>> [x for x, *_ in my_dictionary.values()]
[5, 1, 10]
Or use operator.itemgetter
to select the first item:
>>> from operator import itemgetter
>>> list(map(itemgetter(0), my_dictionary.values()))
[5, 1, 10]
Upvotes: 1
Reputation: 78690
You are probably looking for dict.values
:
>>> [t[0] for t in my_dictionary.values()]
[5, 1, 10]
Upvotes: 6