merge two named tuples

Solutions on MaxInterview for merge two named tuples by the best coders in the world

showing results for - "merge two named tuples"
Mateo
16 Apr 2017
1from collections import namedtuple
2from functools import reduce
3
4
5def reducer( accum, d ):
6   accum.update(d)
7   return accum
8
9def  tuplemerge( *dictionaries ):
10   merged = reduce( reducer, dictionaries, {} )
11   return namedtuple('Merged', merged )(**merged) # <==== Gist of the gist
12
13if __name__ == '__main__':
14    obj1 = { 'a': 1, 'b': 2, 'c': 3 }
15    obj2 = { 'd': 44, 'e': 55, 'f': 66 }
16    obj3 = { 'g': 88, 'h': 99, 'f': 111 } # <=== this 'f' overrides previous 'f'
17    print(tuplemerge( obj1,obj2,obj3 ))