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': 2, '2C': 1, '3E': 2, 'PRODUCT NAME': 'Brown Bread loaf
large', 'Week': 1}...]
I want to create a new dictionary, that looks like this:
new_dict =
[{'HOUSE NAME': '1A', 'White Bread Loaf Large' : 1, 'Brown Bread loaf large' : 1},
{'HOUSE NAME': '1B', 'Brown Bread loaf large' : 1},...
{'HOUSE NAME': '3E', 'White Bread Loaf Large' : 2, 'Brown Bread Loaf Large' : 2}]
Each 'HOUSE NAME' is unique.
I have a solution, that creates the new dictionary, and works with the sample list I've provided, but it does not work for my actual list (that contains 27 dictionaries)
This is the solution:
houses = set(['1A', '1B', '1C', '1D', '3E'])
output_list = []
for house in houses:
output_entry = {}
output_entry["HOUSE NAME"] = house
for entry in my_dicts:
if entry.get(house) and entry.get("PRODUCT NAME"):
product_name = entry.get("PRODUCT NAME")
if output_entry.get(product_name):
output_entry[product_name] += 1
else:
output_entry[product_name] = 1
output_list.append(output_entry)
The solution's last if statement doesnt seem to work, as whatever I set the 'else's condition to, is what my values are set to.
See Question&Answers more detail:
os