在for循环内附加函数列表:对字典所做的更改未生效

问题描述

我有一个字典清单。我想创建一个列表,其中包含每个字典多次(根据其数量)。 但是,每个字典都应具有一个带有ID号的新键值对。

如果试图这样做。

list1 = [{'name':'item A','qty':'3'},{'name':'item B','qty':'5'} ]
new_list_of_dicts = []

for item in list1:

    qty = int(item['qty'])

    for i in range(1,qty+1):
        item['id'] = i
        print(item)
        new_list_of_dicts.append(item)

print (new_list_of_dicts)

但是,即使for循环(项目)中的词典在每次迭代中都包含正确的ID。仅将字典的一个版本添加到新列表(高ID)。 如何解决此问题,以便在新列表中增加数量

各个字典如下:

{'name': 'item A','qty': '3','id': 1}
{'name': 'item A','id': 2}
{'name': 'item A','id': 3}
{'name': 'item B','qty': '5','id': 1}
{'name': 'item B','id': 2}
{'name': 'item B','id': 4}
{'name': 'item B','id': 5}

从列表中创建的数据框为每个零件显示相同的ID

import pandas as pd

df=pd.DataFrame(new_list_of_dicts)
print(df)

结果:

     name qty  id
0  item A   3   3
1  item A   3   3
2  item A   3   3
3  item B   5   5
4  item B   5   5
5  item B   5   5
6  item B   5   5
7  item B   5   5

解决方法

您可以在循环中更改 SAME 词典对象的id。因此,它会更改它的所有版本。为了拥有不同的字典,您需要使用.copy()(如果字典中有字典值,则使用deepcopy())作为新对象进行复制,并使用它来追加:

list1 = [{'name':'item A','qty':'3'},{'name':'item B','qty':'5'} ]
new_list_of_dicts = []
for item in list1:

    qty = int(item['qty'])

    for i in range(1,qty+1):
        #this creates a copy so when you change the id,it only changes the id of this object and not the original item you added.
        item = item.copy()
        item['id'] = i
        new_list_of_dicts.append(item)

print (new_list_of_dicts)

输出:

[{'name': 'item A','qty': '3','id': 1},{'name': 'item A','id': 2},'id': 3},{'name': 'item B','qty': '5','id': 4},'id': 5}]