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:

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

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"]

Leave a Reply