Here's an additional approach, given here, to give you an idea of how Python implements a functional programming method called abbreviation through the reduce()
function. In Python 3, reduce()
is in the functools package . In Python 2, reduce()
is a built-in function . I am using Python 3 in the following example:
from functools import reduce
The first argument to reduce()
is a function to work with iterable, the second is iteration (your list is l
), and the third is an optional initializer object, which is placed at the top of the list
reduce.
At each step of reduction, an object is required that must work: namely, the result of the previous step. But dict.update()
does not return anything, so we need the updater()
function above, which performs the update, and then returns the dict
updated, thereby providing the necessary object for the next step. If it were not for dict.update()
that has no return value, all this would be single-line.
Since dict.update()
works directly with the original dict
, we need this optional empty dict()
initialization object to start undoing - without it, the first dict
in your original list l
will be changed,
For all these reasons, I understand the @MSeifert dict-assrehension approach very well, but I posted this anyway to illustrate the Python shortcut for you.
source share