Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the corresponding item in two tuples with Python

I have a list of tuples containing data, and another corresponding tuple containing some header information. Based on the header, I would like to extract a specific value from a given element in the list. Example:

>>> hdr = ("a", "b", "c", "d", "e")
>>> elt = (1, 2, 3, 4, 5)
>>> my_func(elt, "c")
3

The key here is that I know the header names ahead of time but not their position in the header tuple. What is the easiest way to find the value in elt corresponding to "c" in hdr? I am using Python 3.2.

like image 612
astay13 Avatar asked Dec 21 '25 11:12

astay13


1 Answers

Easiest?

dict(zip(hdr, elt))["c"]

An alternative would be:

elt[hdr.index("c")]

However building a dict (as per the first suggestion) would be more efficient if you're making repeated searches.

like image 162
ecatmur Avatar answered Dec 23 '25 01:12

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!