【问题标题】:Create nested output as below from the given list of dictionaries [duplicate]从给定的字典列表中创建如下嵌套输出[重复]
【发布时间】: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


【解决方案1】:

这应该可行:

suppliers = {}   #Dict with the suppliers
for item in product_list:
    if not item["supplier"] in suppliers.keys():
        suppliers[item["supplier"]] = []   #Add new supplier to suppliers dict
        
    suppliers[item["supplier"]].append(item.copy()) #Add item to supplier
    suppliers[item["supplier"]][-1].pop("supplier", None)  #Remove unwanted fields
    suppliers[item["supplier"]][-1].pop("id", None)

此解决方案有效,但我建议您使用项目及其供应商的类而不是字典。

【讨论】:

  • 我猜你的意思是 item.copy() 而不是 i.copy()
  • 是的,正确的。我会编辑它。
【解决方案2】:

您可以为此使用熊猫。检查以下:

import pandas as pd

res={i:'' for i in set(df.supplier)}

for i in res:
    temp=pd.DataFrame(product_list)
    temp=temp[temp.supplier==i]
    temp=temp[['product_name', 'quantity', 'product_cost']]
    res[i]=temp.to_dict(orient='records')

>>> print(res)

{'Sharp Retail Inc': [{'product_name': 'Samsung TV 32 inch', 'quantity': 1, 'product_cost': 30000}, {'product_name': 'Sony Headphones ', '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}]}

【讨论】:

  • 请停止在您的帖子下方发布相同的“OP,请您接受一些答案”cmets。它们没有任何作用,只是在网站上增加噪音。
  • 好的,我会的。我认为对于正确回答但未接受答案的问题进行“跟进”是一种常见做法 (meta.stackexchange.com/questions/88535/…)
猜你喜欢
  • 2020-01-23
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2021-11-20
  • 2021-04-19
  • 2018-01-16
相关资源
最近更新 更多