Skip to content

Instantly share code, notes, and snippets.

@arshpreetsingh
Created November 9, 2021 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arshpreetsingh/54e66c2e1726976d12a420f4bcf5684c to your computer and use it in GitHub Desktop.
Save arshpreetsingh/54e66c2e1726976d12a420f4bcf5684c to your computer and use it in GitHub Desktop.
nest dict algo
from collections import defaultdict
from itertools import chain
from operator import methodcaller
# dictionaries with non-equal keys, values all lists for simplicity
one = {'a': {1, 2}, 'c': [5, 6], 'b': [3, 4], 'e': [6.2]}
two = {'a': {2.4, 3.4}, 'c': [5.6, 7.6], 'b': [3.5, 4.5], 'f': [1.3]}
three = {'a': [1.2], 'c': [3.4], 'b': [2.3], 'e': [3.1],'f':[1,2,3,4,5]}
dict_list = [one,two,three]
# initialise defaultdict of lists
dd = defaultdict(list)
# iterate dictionary items
dict_items = map(methodcaller('items'), (dict_list))
for k, v in chain.from_iterable(dict_items):
dd[k].extend(v)
print(dict(dd))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment