我正在尝试转换此列表:
list = [
{'product_name': '4x6', 'quantity': 1, 'price': 0.29},
{'product_name': '4x6', 'quantity': 1, 'price': 0.29},
{'product_name': '4x6', 'quantity': 1, 'price': 0.29},
{'product_name': '4x6', 'quantity': 1, 'price': 0.29},
{'product_name': '4x4', 'quantity': 1, 'price': 0.29},
{'product_name': '4x4', 'quantity': 1, 'price': 0.29},
{'product_name': '4x4', 'quantity': 1, 'price': 0.29},
{'product_name': '4x4', 'quantity': 1, 'price': 0.29},
]
输入键“product_name”上的出现次数总和,如下所示:
list_final = [
{'product_name': '4x6', 'quantity': 4, 'price': 1.16},
{'product_name': '4x4', 'quantity': 4, 'price': 1.16},
]
我不知道如何在不循环中搜索键“product_name”的出现
我做了什么:
for item in list:
if item.product_name in data.keys():
data[item.product_name]['qty'] += 1
data[item.product_name]['price'] *= 2
else:
data.update({item.product_name: [{'qty': item['quantity'], 'price': item['price']}]})
但我找不到解决方案来获取我想要的列表
我怎样才能正确地做到这一点?
最佳答案
这是一个使用 OrderedDict
处理多个产品的解决方案。
from collections import OrderedDict
o = OrderedDict()
for x in data:
p = x['product_name']
if p not in o:
o[p] = x
else:
o[p].update({k : o[p][k] + x[k] for k in x.keys() - {'product_name'}})
list_final = list(o.values())
如果产品不存在,则将其添加到库存中,否则将与现有库存相加。这应该适用于 python3.x 及更高版本。
print(list_final)
[{'price': 1.16, 'product_name': '4x6', 'quantity': 4}]
对于 python2.x,更改此
o[p].update({k : o[p][k] + x[k] for k in x.keys() - {'product_name'}})
至
o[p].update({k : o[p][k] + x[k] for k in set(x.keys()) - {'product_name'}})
关于python - 在Python中查找对象列表中出现的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46953090/