0

Im using Python 3.9. I need to merge multiple dictionaries with list values into appending the array value to each key

{'xx5.8.38': ['testingxyz-597247']}
{'xx5.8.38': ['testingxyz-597624']}
{'xx5.8.38': ['testingxyz-597626']}
{'xx1.0.3': ['testingxyz-597247']}
{'xx1.0.3': ['testingxyz-597624']}
{'xx1.0.3': ['testingxyz-597626']}
(several more dicts)

Result should be:

{'xx5.8.38': ['testingxyz-597247', 'testingxyz-597624', 'testingxyz-597626']}
{'xx1.0.3': ['testingxyz-597247', 'testingxyz-597624', 'testingxyz-597626']}
gyranta
  • 11
  • 1
  • 1
    And what is the question? Which part of this task is not working for you? Do you have some code which does not work as expected? – zvone Nov 01 '20 at 21:14

1 Answers1

1

You could use a collections.defaultdict

from collections import defaultdict

input_dirs = [{'xx5.8.38': ['testingxyz-597247']},
              {'xx5.8.38': ['testingxyz-597624']},
              {'xx5.8.38': ['testingxyz-597626']},
              {'xx1.0.3': ['testingxyz-597247']},
              {'xx1.0.3': ['testingxyz-597624']},
              {'xx1.0.3': ['testingxyz-597626']}]


result_dir = defaultdict(list)
for single_dir in input_dirs:
    for key, val in single_dir.items():
        result_dir[key].extend(val)

giving you

defaultdict(<class 'list'>,
            {'xx1.0.3': ['testingxyz-597247',
                         'testingxyz-597624',
                         'testingxyz-597626'],
             'xx5.8.38': ['testingxyz-597247',
                          'testingxyz-597624',
                          'testingxyz-597626']})
Simon Fromme
  • 3,104
  • 18
  • 30