user12394113
user12394113

Reputation: 401

Select specific elements from a dictionary with tuple values

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

Answers (3)

Aditya Patnaik
Aditya Patnaik

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:

  • loops over keys
  • takes the mentioned index value of the tuple for every class

Code Profile

  • Takes 88 bytes and 275ns for a 1000 key/value pairs

Why is it so memory efficient?

  • Because of the use of generators.

code profile

Upvotes: 0

RoadRunner
RoadRunner

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

timgeb
timgeb

Reputation: 78690

You are probably looking for dict.values:

>>> [t[0] for t in my_dictionary.values()]
[5, 1, 10]

Upvotes: 6

Related Questions