是否可以从其他字典创建字典?
我有一个字典列表,看起来像这样:
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}...]
我想创建一个字典,它看起来像这样:
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}]
基本上我想要键'HOUSE NAME',每个家喻户晓的值,'my_dicts' 'PRODUCT NAME'作为键,值是HOUSE names'值(即1)
不确定您的意思,但我建议您在House_Name值中使用列表以字符串格式保存PRODUCT NAME值
我的答案只有一个先决条件那就是你有一个房子IDs
的集合/唯一列表
my_dicts = [{
'1A': 1,
'3E': 2,
'PRODUCT NAME': 'White Bread loaf large',
'Week': 1
}, {
'1A': 1,
'1C': 2,
'PRODUCT NAME': 'White Bread loaf large',
'Week': 1
}, {
'1A': 1,
'1B': 1,
'1C': 1,
'1D': 2,
'PRODUCT NAME': 'Brown Bread loaf large',
'Week': 1
}]
# !:Prerequisite you have the IDs as a unique set
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)
print(output_list)
您可以使用map
和filter
使其更简洁
输出:
[
{'HOUSE NAME': '1A', 'White Bread loaf large': 2, 'Brown Bread loaf large': 1},
{'HOUSE NAME': '1C', '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': 1},
{'HOUSE NAME': '1D', 'Brown Bread loaf large': 1}
]
这只是为了显示
map
和filter
如何在OP的请求下工作,请不要这样做,因为它使代码不太可读,不符合python
from functools import reduce
...
output_entry["HOUSE NAME"] = house
output_entry = {
**output_entry,
**dict(
reduce(
lambda x, y: {
k: x.get(k, 0) + y.get(k, 0)
for k in set(x) | set(y)
}, (map(
lambda x: {x["PRODUCT NAME"]: 1},
filter(lambda x: x.get(house) and x.get("PRODUCT NAME"), my_dicts)))))
}
output_list.append(output_entry)
print(output_list)
...