Home > Blockchain >  Whats most pythonic way of colelcting second object of tuple in dictionary into a list
Whats most pythonic way of colelcting second object of tuple in dictionary into a list

Time:03-17

I have following objects

a = ("one", 1)
b = ("two", 2)
c = ("seven", 7)
my_dict = {10: a, 20:b, 70:c}

I want to get a list of [1, 2, 7] from my_dict. Whats the most pythonic way to do so?

CodePudding user response:

Just use list comprehension. It's the most pythonic way of doing most things ;)

output = [x[1] for x in my_dict.values()]

CodePudding user response:

If you like the functional way, you could use:

list(zip(*my_dict.values()))[1]

Output: (1, 2, 7)

Or, as list:

list(list(zip(*my_dict.values()))[1])

Output: [1, 2, 7]

CodePudding user response:

You can use tuple unpacking inside the list comprehension to avoid having to index into the tuple:

result = [item for _, item in my_dict.values()]
print(result)

This prints:

[1, 2, 7]

CodePudding user response:

Another "functional" approach, just for kicks:

from operator import itemgetter as get

output = list(map(get(1), my_dict.values()))
  • Related