Question

In python namedtuple, how can I get all values with the same name?

eg. : [tup(a = 1, b=2), tup(a = 2, b=5), tup(a = 3, b=2)]

How can I get all a's or all b's?

Also, is it possible to get all tuples with b == 2 ?

Was it helpful?

Solution

List comprehensions for the win:

all_b_values = [t.b for t in list_of_named_tuples]
all_a_values = [t.a for t in list_of_named_tuples]

or

all_b_2s = [t for t in list_of_named_tuples if t.b == 2]

There is nothing namedtuple-specific about these list comprehensions; they work for any sequence of objects with common attributes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top