Created
November 9, 2021 02:18
-
-
Save arshpreetsingh/54e66c2e1726976d12a420f4bcf5684c to your computer and use it in GitHub Desktop.
nest dict algo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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