我有这个对象data_listmedia
:
print(data_listmedia) :
[{'id': 6, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 30, 'date': datetime.date(2020, 9, 25)}, {'id': 7, 'withdegrey_id': 2, 'withsecondray_id': 2, 'nomberesteda': 400, 'nomberhodor': 200, 'date': datetime.date(2020, 9, 25)}, {'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}]
现在,我想将此人格字典附加到此列表中的所有字典上,因此我使用此循环:
首先我宣布
mydict ={}
data = []
for l in data_listmedia:
persontage = ((l["nomberhodor"] * 100) / l["nomberesteda"])
mydict.update({"percontage": persontage})
data.append(mydict)
mydict.update(l)
但是在完成循环时,它将追加列表中的最后一个字典
print(data)
[{'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}, {'percontage': 60.0, 'id': 8, 'withdegrey_id': 1, 'withsecondray_id': 2, 'nomberesteda': 200, 'nomberhodor': 120, 'date': datetime.date(2020, 9, 25)}]
为什么当我使用data.append(mydict)
时,它会重复全部列表中的最后一个字典?
但是当我使用
print(persontage)
在循环内 价值实现
7.5
50.0
60.0
如何将字典添加到列表中而不重复?
答案 0 :(得分:1)
您将在列表中添加相同的字典引用,因此基本上每个元素都指向内存中的相同字典。要在更高级别解决此问题,请执行以下操作:
new_dict = dict(my_dict)
并使用“ new_dict”。