Search code examples
pythonpython-2.7listsimplifysimplification

Simplifying code of complex list comprehension in Python


Assume a list of dictionaries (lst_of_dcts) in Python. Further, assume that I wish to modify (e.g., encode in ASCII) each value v of the key-value pairs k:v in each of the dictionaries dcts. In order to do so, I am using list comprehension, but the code line becomes quite long and difficult to read.

import unidecode
[{k: unidecode.unidecode(v.decode('utf-8')) for k, v in dct.items()} for dct in lst_of_dcts]

How would you split the above list comprehension into shorter, easier-to-read lines? (Please note that I don't mean to simply reformat the lines via, for example, backward slashes.)


Solution

  • Please note that I don't mean to simply reformat the lines via, for example, backward slashes.

    Why not? That's exactly what I'd do to make it more readable. Properly indented, of course, to show the structure:

    [{k: unidecode.unidecode(v.decode('utf-8'))
      for k, v in dct.items()}
     for dct in lst_of_dcts]