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)
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
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.
NameError: global name 'encod' is not definedYour 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))
AttributeError: 'generator' object has no attribute 'next'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()]
encod that matches your criteria to a list that you could then .join() if you'd like?