arynhard
arynhard

Reputation: 542

pythonic way of handling nested for loop

I have the following code and for the sake of learning would like to see a more pythonic way of achieving this:

for value in response.values():
    for encod in encodings:
        if encod.lower() in value.lower():
            return(encod)

Upvotes: 0

Views: 216

Answers (5)

A.E. Drew
A.E. Drew

Reputation: 2137

Just to offer another approach using a Cartesian product. I like this because it matches the way I would think: "check every pair of values."

    import itertools
    for (encoding, value) in itertools.product(encodings, response.values()):
        if encoding.lower() in value.lower():
            return encoding

Upvotes: 0

arshajii
arshajii

Reputation: 129497

If you're looking for a different way, you can use this:

return next(encod for value in response.values() 
                      for encod in encodings 
                          if encod.lower() in value.lower())

The portion within next(...) is a generator expression that yields each encod in encodings for each value in response.values() if the condition encod.lower() in value.lower() is satisfied. The first element of this generator is what we return (see next()).

Although, in practice, I would generally go with what you already have. It's the simplest and clearest way to do what you are trying to do, and is by no means unpythonic.

Upvotes: 4

schesis
schesis

Reputation: 59118

Assuming that you actually intend to return only the first match you find (which is what your code does), there's nothing unpythonic about your code except the unnecessary parentheses in the last line, which you can replace with:

            return encod

Pythonic does not mean 'write a one-liner' or 'use a particular feature of Python for the sake of it'. It means, among other things, 'write your code in the most easily-understood and expressive way that you can'.

See also: the Zen of Python

Upvotes: 10

Silas Ray
Silas Ray

Reputation: 26150

Your code will only return the first matching instance, but you could still use a list comprehension or better, a generator expression.

return next(v for v in response.values() if v.lower in map(lower, encodings))

Upvotes: 1

Al.Sal
Al.Sal

Reputation: 984

Are you OK with outputting it as a list? A list comprehension would make it more Pythonic.

return [encod for value in response.values() for encod in encodings if encod.lower() in value.lower()]

Upvotes: 0

Related Questions