I needed to flatten a dictionary today. Meaning I wanted:
{'_id': 0, 'sub': {'a': 1, 'b':2}}
to become:
{'_id': 0, 'a':1, 'b':2}
So I thought I could be clever and pull off the following one-liner.
One-liner:
x = dict(_id=0, sub=dict(a=1, b=2))
y = x.pop('sub').update(x) # incorrect result
This results in y = None
.
So I obviously resorted to:
Multi-Step:
x = dict(_id=0, sub=dict(a=1, b=2))
y = x.pop('sub')
y.update(x) # correct result
Setting "good expressive coding practices" asside for a moment, I would like to understand why the One-liner approach above yields None
. I would have thought that x.pop('sub') would have resulted in a temporary dict on a stack somewhere and the original x dict would be immediately updated. Then the stack object would receive the next method in the chain which is the update. This obviously does not seem to be the case.
For the communities better understanding (and clearly mine) - how does python resolve the one-liner and result in None?