Skip to content Skip to sidebar Skip to footer

Creating A New Dictionary From A List Of Dictionaries

I have a list of dictionaries, that looks like this: my_dicts = [{'1A': 1, '3E': 2, 'PRODUCT NAME': 'White Bread loaf large', 'Week': 1}, {'1A': 1, '1B': 1, '1C': 1, '1D': 2, '1E

Solution 1:

You could do it like this:

my_dicts = [{'1A': 1, '3E': 2, 
             'PRODUCT NAME': 'White Bread loaf large', 'Week': 1},
            {'1A': 1, '1B': 1, '1C': 1, '1D': 2, '1E': 2, '2C': 1, '3E': 2,
             'PRODUCT NAME': 'Brown Bread loaf large', 'Week': 1}]

merged = dict()
for d in my_dicts:
    for k,v in d.items():
        if k in ('PRODUCT NAME','Week'): continue# only process house names
        merged.setdefault(k,{'HOUSE NAME':k}).update({d['PRODUCT NAME']:v})
result = list(merged.values())

print(result)

[{'HOUSE NAME': '1A', 'White Bread loaf large': 1, 'Brown Bread loaf large': 1},
 {'HOUSE NAME': '3E', 'White Bread loaf large': 2, 'Brown Bread loaf large': 2},
 {'HOUSE NAME': '1B', 'Brown Bread loaf large': 1},
 {'HOUSE NAME': '1C', 'Brown Bread loaf large': 1},
 {'HOUSE NAME': '1D', 'Brown Bread loaf large': 2},
 {'HOUSE NAME': '1E', 'Brown Bread loaf large': 2},
 {'HOUSE NAME': '2C', 'Brown Bread loaf large': 1}]

The merged dictionary serves as a temporary index to assemble the new list of dictionaries by updating them based on each house name. Then the final result is obtained by ignoring the indexing par of merged, only taking the values (i.e. dictionaries merged by house)

Post a Comment for "Creating A New Dictionary From A List Of Dictionaries"