2

I have a namedtuple, that contains several namedtuples within it.

Each of the inner tuples essentially has a unique 'id', along with other useful information. I know the ID of the tuple I want to access, and Im wondering if there's an easy way to 'index' the namedtuple to extract the exact element I want without doing something like:

for inner_tuple in outer_tuple:
    if inner_tuple.id == desired_id:
        found tuple = inner_tuple
        break
e wagness
  • 301
  • 2
  • 13
  • 1
    It sounds like you want to store them in a dictionary. Set the key as the id. – GP89 Sep 13 '13 at 17:49
  • 1
    If you could sort the outer tuple, you could do a binary search. You could also easily build a separate dictionary that mapped each id directly to its index in the outer tuple. Otherwise you'll need to completely replace the outer tuple with another data structure, like a dictionary. – martineau Sep 13 '13 at 17:55
  • Also related: https://stackoverflow.com/q/12087905/1736679 – Efren Jul 14 '22 at 03:48

1 Answers1

4

You can use a generator expression with next() to find the first match, or None if nothing matched. This still requires a loop:

found = next((tup for tup in outer_tuple if tup.id == desired_id), None)

The alternative is to use a dictionary keyed on id instead.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343