我正在尝试使用理解列表将一个词典列表嵌套到另一个词典列表中,我有两个词典列表,一个是类别,另一个是油脂。如果油类category_id等于类别ID,则将清单油的结果添加到每个类别。
def nest(parent, child):
items = []
for element in child:
if element.get('category_id') == parent.get('id'):
items.append(element)
parent.update({'items': items})
return parent
def merge(parent, child):
results = []
for element in parent:
results.append(nest(element, child))
return results
categories = [
{'id': 1000, 'name': 'Single'},
{'id': 2000, 'name': 'Blend'}]
oils = [
{'id': 100, 'name': 'Orange', 'category_id': 1000},
{'id': 101, 'name': 'Lavender', 'category_id': 1000},
{'id': 102, 'name': 'Peppermint', 'category_id': 1000},
{'id': 104, 'name': 'Inspired', 'category_id': 2000},
{'id': 105, 'name': 'Focus', 'category_id': 2000},
{'id': 107, 'name': 'Tea Tree', 'category_id': 1000}]
results = merge(categories, oils)
print(results)
# output:
# [
# {'id': 1000, 'name': 'Single', 'items': [
# {'id': 100, 'name': 'Orange', 'category_id': 1000},
# {'id': 101, 'name': 'Lavender', 'category_id': 1000},
# {'id': 102, 'name': 'Peppermint', 'category_id': 1000},
# {'id': 107, 'name': 'Tea Tree', 'category_id': 1000}
# ]},
# {'id': 2000, 'name': 'Blend', 'items': [
# {'id': 104, 'name': 'Inspired', 'category_id': 2000},
# {'id': 105, 'name': 'Focus', 'category_id': 2000}
# ]}
# ]
我正在尝试将以上内容转换为理解列表,但没有成功
merged = [
element.update({'items': nest}) for nest in oils
for element in categories if element.get('id') == nest.get('category_id')
]
print(merged)
# output: [None, None, None, None, None, None]
merged = [dict(**c, items=[o for o in oils if o['category_id'] == c['id']]) for c in categories]
from pprint import pprint
pprint(merged)