Reputation: 542
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
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
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
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
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
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