Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add list within list while creating a new 'label'

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{'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

>Solution :

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}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading