Home > Enterprise >  Adding multiple elements to dictionary inside the list and appending the dictionary every time and e
Adding multiple elements to dictionary inside the list and appending the dictionary every time and e

Time:05-25

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

CodePudding user response:

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)

CodePudding user response:

This should work too:

brand = [1,2,3]
r = list()
for i in brand:
    r.append(dict(time=1, id=1, region=[dict(brand=i)]))

Output:

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

And if you want you can set the values of 'time' and 'id' just like 'region':

brand = [1,2,3]
r = list()
for i in brand:
    r.append(dict(time=i, id=i, region=[dict(brand=i)]))

CodePudding user response:

You can also do something like that:

brand = [1, 2, 3]
r = [{'time': 1, 'id': 1, 'region':[{"brand": i}]} for i in brand]
  • Related