迭代一个List,并将值添加到Dictionary中的List中,并为每次迭代清除它



我有一个python字典和一个python列表。

dictionary=
{
"a":"A",
"b":"B",
"c":"C",
"Test":[]
}

我还有一个python列表,

list=["1","2","3","4"]

如何生成

[{
"a":"A",
"b":"B",
"c":"C",
"Test":["1"]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":["2"]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":["3"]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":["4"]
}]

如果这是个愚蠢的问题,饶了我吧。

这里有一些步骤和想法,但大体上是

  • 启动一个新列表,将最终结果打包到
  • 迭代列表(列表已经是可迭代的(
  • 在每个循环中复制dict(否则它将操纵原始dict(
list_dest = []
for member in list_src:
sub_dict = dict_src.copy()  # must copy.deepcopy for deeper members
sub_dict["Test"] = [member]  # new list with only the list member
list_dest.append(sub_dict)
# list_dest is now the desired collection

另外

  • 不要重写像list这样的内置,因为当您稍后尝试引用它们时,它可能会变得令人困惑
  • 如果您想获得比源dict的顶部内容更深入的深度,则应该使用copy.deepcopy(),否则仍将引用原始成员

一个简单的短代码实现方法是:

my_list = ["1","2","3","4"]
dictionary={"a":"A","b":"B","c":"C","Test":[]}
list_of_dictionnaries = []
for e in my_list:
dictionary["Test"] = [e]
list_of_dictionnaries.append(dictionary.copy())
print(list_of_dictionnaries)

list是一个内置函数,您不应该将变量命名为内置函数,而应该将其命名为my_listmy_indices

这应该有效:

dictionary= {
"a":"A",
"b":"B",
"c":"C",
"Test":[]
}
list=["1","2","3","4"]
result = []
for item in list:
single_obj = dictionary.copy()
single_obj["Test"] = [item]
result.append(single_obj)
print(result)

输出:

[
{
"a":"A",
"b":"B",
"c":"C",
"Test":[
"1"
]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":[
"2"
]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":[
"3"
]
},
{
"a":"A",
"b":"B",
"c":"C",
"Test":[
"4"
]
}
]

您可以这样做:

dictionary={
"a":"A",
"b":"B",
"c":"C",
"Test":[]
}
l_=[]
list2=["1","2","3","4"]
for i in list2:
dict1=dictionary.copy() #==== Create a copy of the dictionary 
dict1['Test']=[i] #=== Change Test value of it.
l_.append(dict1) #=== Add the dictionary to l_
print(l_)
d = {c: c.upper() for c in 'abc'}
L = [d.copy() for _ in range(4)]
for i, d in enumerate(L):
d['Test'] = [str(i+1)]

最新更新