Home > Net >  Add list within list while creating a new 'label'
Add list within list while creating a new 'label'

Time:04-08

I have 2 lists; or at least, I believe they are lists:

one = [{'sex': 'M', 'age': 22},
      {'sex': 'M', 'age': 76},
      {'sex': 'F', 'age': 37},
      {'sex': 'F', 'age': 45}]

two = [0, 1, 0, 0]

I want to append the list two to the list one while creating a new 'label'.

The desired output should look like this (and still be a list):

[{'sex': 'M', 'age': 22, 'new label': 0},
 {'sex': 'M', 'age': 76, 'new label': 1},
 {'sex': 'F', 'age': 37, 'new label': 0},
 {'sex': 'F', 'age': 45, 'new label': 0}]

This must be easy but I can't make it work and couldn't use closely related answers on so. Using just .append(two) put list two at the end of list one of course, instead of inserting it within list one.

Feel free to flag as duplicate if needed, but please help with this particular example! Many thanks

CodePudding user response:

for d, v in zip(one, two):
    d["new_label"] = v

one
# [{'sex': 'M', 'age': 22, 'new_label': 0},
#  {'sex': 'M', 'age': 76, 'new_label': 1},
#  {'sex': 'F', 'age': 37, 'new_label': 0},
#  {'sex': 'F', 'age': 45, 'new_label': 0}]

CodePudding user response:

one is a list of dictionaries. What you want to do is step through the dictionaries in said list, and append the values from two to it.

for i in range(0,len(one)):
    one[i]['age'] = two[i]

This steps through each dictionary in the list, and appends your new key-value pair to it.

CodePudding user response:

So the first one is a list of dictionaries and the other is a list.

one = [{'sex': 'M', 'age': 22},
  {'sex': 'M', 'age': 76},
  {'sex': 'F', 'age': 37},
  {'sex': 'F', 'age': 45}]

two = [0, 1, 0, 0]

for count, i in enumerate(one):
    i['new label'] = two[count]

That would be how I would do it. You can use enumerate to keep track of where you are in the loop.

  • Related