0

I have a python dictionary and a python list.

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

I also have a python list,

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

How Can I generate

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

Spare me If it is a silly question.

RajNikhil Marpu
  • 397
  • 2
  • 4
  • 19

5 Answers5

1

there's a few steps and some ideas here, but broadly

  • start a fresh list to pack the final results into
  • iterate over the list (lists are already iterable)
  • copy the dict at each cycle (otherwise it'll manipulate the original one)
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

additionally

  • don't override builtins like list, as it can become confusing when you attempt to reference them later
  • if you wanted to get more depth than the top contents of the source dict, you should use copy.deepcopy(), or you'll still have references to the original members
ti7
  • 16,375
  • 6
  • 40
  • 68
1

An easy way to do this in short line is the following code:

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 is a built-in function, you should never name your variables as built-in functions, instead, name it something like my_list, or my_indices.

Samir Ahmane
  • 830
  • 7
  • 22
0

This should work:

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)

Output:

[
   {
      "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"
      ]
   }
]
dchoruzy
  • 249
  • 2
  • 8
0

You can do something like this:

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_)
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)]
Lars
  • 1,869
  • 2
  • 14
  • 26