Search code examples
python-3.xlistsyntaxlist-comprehension

Why is this Python list comprehension failing?


Why does the following code fail? I'm getting a 'd_item' is not defined error.

inp = [{'Math': 90, 'Science': 92}, {'Math': 89, 'Science': 94}, {'Math': 92, 'Science': 88}]
d = [value for key, value in d_item.items() for d_item in inp]

Yet this code runs:

inp = [{'x': '10', 'y': '20', 'z': '30'}, {'p': '40', 'q': '50', 'r': '60'}] 
ints = [dict([key,int(value)] for key, value in item.items()) for item in inp]

They both follow the same convention as far as I can tell.

I've been stuck on this for too long, why does the second code block let me use a variable name before its stated in a for statement but the first one does not?


Solution

  • Start by reading this: How does the list comprehension to flatten a python list work?

    It is a pretty good explanation of how nested things are handled.

    So your syntax should be:

    d = [value for d_item in inp for key, value in d_item.items() ]
    

    as for why the second works, the dict creation is 1 expression (with an internal loop), based on the implicit (single) loop next to it.

    ints = [dict([key,int(value)] for key, value in item.items()) for item in inp]
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^      ^^^^^^^^^^^
                    single expression (with internal loop)              for-loop