I’m new in python, and just ran into this statement
data = dict( (k, v) for k, v in data.items() if v != 'null')
I don’t really what they doing here to construct a dict. Could you explain it a bit to me? Why using for loop in dict() and why the if comes after? I didn’t see anythin like this in the python docs.
Thanks guys
The code uses the
dictconstructor to create a new dictionary. The constructor can take an iterable of key, value pairs to initialise the new dictionary with. As others have pointed out, the example code has a generator expression the creates this iterable of key, value pairs.The generator expression acts a little bit like a list and could be re-written like this:
But it never actually creates a list, it just yields each value in turn as it is processed by the dict constructor.
As for why the
ifcomes after the loop, this is the syntax chosen by the python developers, so you’d have to ask them. But notice in my re-written generator expression that theifstatement is inside (i.e. after) the for statement.I’ve linked already to the section on generator expressions in the python documentation but at unkulunkulu’s request, here’s a couple more: