【发布时间】:2020-11-08 15:10:29
【问题描述】:
product_list = [
{ 'id': 1,'product_name': 'Nokia 6.1','supplier': 'W3 Retail Inc','quantity': 1, 'product_cost': 10000 },
{ 'id': 1,'product_name': 'Samsung TV 32 inch', 'supplier': 'Sharp Retail Inc','quantity': 1, 'product_cost': 30000 },
{'id': 1, 'product_name': 'Nokia 1100', 'supplier': 'W3 Retail Inc', 'quantity': 4, 'product_cost': 8000 },
{ 'id': 1, 'product_name': 'Sony Headphones ','supplier': 'Sharp Retail Inc','quantity': 1,'product_cost': 750 }
]
输出:
[{'W3 Retail Inc' : [{'product_name': 'Nokia 6.1', 'quantity': 1, 'product_cost': 10000},
{'product_name': 'Nokia 1100', 'quantity': 4, 'product_cost': 8000}],
'Sharp Retail Inc' : [{'product_name': 'Samsung TV 32 inch', 'quantity': 1, 'product_cost': 30000},
{'product_name': 'Sony Headphones ', 'quantity': 1, 'product_cost': 750}]
}],
我花了一些时间尝试将上面的product_list 转换为上面的输出。
我试过这个:
new_dict = {element['supplier'] : [element.items() for element in product_list if element.keys not in ('id','supplier',)] for element in product_list}
但这不是我想要的输出。请帮我解决。
【问题讨论】:
-
有必要把所有的东西写在一行吗?你知道代码可读性也很重要。
标签: python python-3.x