我有一个 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"]
}]
如果这是一个愚蠢的问题,请原谅我。
答案 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_list
或 my_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)]