Home > Blockchain >  Is there a one-line code that can collects the first element of a tuple of a dict?
Is there a one-line code that can collects the first element of a tuple of a dict?

Time:04-29

For example,

my_dict = {'a':(1,2), 'b':(3,4), 'c':(5,6)}

I want to get a list of:

[1,3,5]

Is there a one-line code that can extract the values? I have to do this way:

values = [v[0] for v in list(my_dict.values())]

Is there an even better way than this line?

CodePudding user response:

Since you only want the first elements, another option could be to use zip and next:

out = [*next(zip(*my_dict.values()))]

Output:

[1, 3, 5]

That said, your version is much more readable and what I would use for myself.

CodePudding user response:

A list comprehension is the best way to go both for readability and performance:

[t[0] for t in my_dict.values()]

CodePudding user response:

The next() solution from @enke is fantastic, but would only work for when you want the first item. Similarly, tuple unpacking would only be feasible if the tuples are relatively small. This solution gives you control over grabbing any element:

>>> from operator import itemgetter as get

>>> [*map(get(0), my_dict.values())]
[1, 3, 5]
  • Related