'Is there a one-line code that can collects the first element of a tuple of a dict? [closed]

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?



Solution 1:[1]

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

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

Solution 2:[2]

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.

Solution 3:[3]

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]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rafael de Bem
Solution 2
Solution 3 ddejohn