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

Split the elements in the list into separate lines with same data in list of dict

I want to separate the data as in the title with Python, namely is:

My data is list of dict:

my_list = [{"info": ["student A", "idA"], "class": "A1"},
           {"info": ["student B", "idB"], "class": "A2"}]

I want result is:

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

my_list = [{"info": "student A", "class": "A1"}, 
           {"info": "idA", "class": "A1"},
           {"info": "student B", "class": "A2"},
           {"info": "idB", "class": "A2"}]

I don’t know how to solve it yet. Is there any way I can get the result?

>Solution :

It helps to describe in words what you need to do. Then draw a flowchart of the process. Then try to write code.

In this case, you have multiple items in my_list. Each item is a dictionary that contains a list of "info" and a single "class".

You want to create a new_item for each student in item['info'], with the same class as item['class'].

output = [] # Empty list to hold output

for item in my_list:                  # Iterate over items in my_list
    for student in item["info"]:      # for each student 
        # create the new item
        new_item = {"info": student, "class": item["class"]}
        # append it to output
        output.append(new_item)

Which gives your desired output:

[{'info': 'student A', 'class': 'A1'},
 {'info': 'idA', 'class': 'A1'},
 {'info': 'student B', 'class': 'A2'},
 {'info': 'idB', 'class': 'A2'}]

Once you’re more comfortable with python, you can write this as a list comprehension:

output = [  {"info": student, "class": item["class"]}
    for item in my_list
    for student in item["info"]
]
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