Search code examples
pythonfor-loopif-statementfor-in-loop

One line conditional assignment if statement


This is the first question I am asking on this forum, so I welcome your feedback on making this more helpful to others.

Say I have this list:

IDs = ['First', 'Second', 'Third']

and this dictionary:

statistics = {('First', 'Name'):"FirstName", ('Second','Name'):"SecondName", ('Third','Name'):"ThirdName"}

Is there a shorter, easier to read one-liner than the following?

firstID = IDs[[statistics[ID,'Name'] for ID in IDs].index('FirstName')]

Many thanks


Solution

  • A more efficient (and probably more readable) approach would be this:

    firstID = next(id for id in IDs if statistics[(id,'Name')]=='FirstName')
    

    This defines a generator which checks the IDs in order, and yields values from statistics that equal "FirstName". next(...) is used to retrieve the first value from this iterator. If no matching name is found, this will raise StopIteration.