Skip to content
Advertisement

Adding multiple elements to dictionary inside the list and appending the dictionary every time and element is added

brand = [1,2,3]

consider this is the list I want to add to the list of dictionaries below

r = [{'time':1,
     'id':1
     'region':[{brand:1}]}]

and every time I add the element I want the dictionary to create new dictionary within the list Exampel:

r = [{'time':1,
     'id':1
     'region':[{brand:1},
    {'time':1,
     'id':1
     'region':[{brand:2}]
     {'time':1,
     'id':1
     'region':[{brand:3}]}

I am new to python and not able to figure out how to do it. Thanks in advance

Advertisement

Answer

This should work:

l = [1,2,3]
r = []
for i in l:
  new_dict = {'time':1, 'id':1, 'region':[{"brand":i}]}
  r.append(new_dict)

Output:

[{'id': 1, 'region': [{'brand': 1}], 'time': 1},
 {'id': 1, 'region': [{'brand': 2}], 'time': 1},
 {'id': 1, 'region': [{'brand': 3}], 'time': 1}]

Edit To address you question in the comment: bear in mind that this will always work in as much as brand and time are of the same length.

brand = [1,2,3]
time = [1,2,3]
r = []
for i in range(len(l)):
  new_dict = {'time':time[i], 'id':1, 'region':[{"brand":brand[i]}]}
  r.append(new_dict)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement