迭代一个列表并将值添加到字典中的列表中,并在每次迭代时清理它

时间:2021-07-07 16:53:23

标签: python python-3.x 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"]
}]

如果这是一个愚蠢的问题,请原谅我。

5 个答案:

答案 0 :(得分:1)

这里有几个步骤和一些想法,但大致上

  • 开始一个新的列表,将最终结果打包到
  • 遍历列表(列表已经是可迭代的)
  • 在每个周期复制字典(否则它会操纵原始的)
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 这样的内置函数,因为当您稍后尝试引用它们时可能会造成混淆
  • 如果你想获得比源字典顶部内容更深入的内容,你应该使用 copy.deepcopy(),否则你仍然会有 references to the original members

答案 1 :(得分:1)

在短行中执行此操作的简单方法是以下代码:

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 之类的名称。

答案 2 :(得分:0)

这应该有效:

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"
      ]
   }
]

答案 3 :(得分:0)

你可以这样做:

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_)

答案 4 :(得分:0)

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)]