Home > Back-end >  How to combine a list of lists into a dictionary where the first sublist is mapped to corresponding
How to combine a list of lists into a dictionary where the first sublist is mapped to corresponding

Time:06-16

I have a list of lists, where the first list is a 'header' list and the rest are data lists. Each of these 'sub' lists are the same size, as shown below:

list1 = [
    ["Sno", "Name", "Age", "Spirit", "Status"],
    [1, "Rome", 43, "Gemini", None],
    [2, "Legolas", 92, "Libra", None]
]

I want to merge all of these 'sub' lists into one dictionary, using that first 'sub' list as a header row that maps each value in the row to a corresponding value in subsequent rows.

This is how my output should look:

result_dict = {
    1: {"Name": "Rome", "Age": 43, "Spirit": "Gemini", "Status": None},
    2: {"Name": "Legolas", "Age": 92, "Spirit": "Libra", "Status": None}
}

As you can see, 1, 2, etc. are unique row numbers (they correspond to the Sno column in the header list).


So far, I am able to get every second element as the key using this code:

list1_as_dict= {p[0]:p[1:] for p in list1}

print(list1_as_dict)

Which outputs:

{
    'Sno': ['Name', 'Age', 'Spirit', 'Status'],
    1: ['Rome', 43, 'Gemini', None],
    2: ['Legolas', 92, 'Libra', None]
}

But I don't know how make each of the data 'sub' lists a dictionary mapped to the corresponding headers.

How can I get my desired output?

CodePudding user response:

Something like

spam = [["Sno","Name","Age","Spirit","Status"],[1, "Rome", 43,"Gemini",None],[2,"Legolas", 92, "Libra",None]]
keys = spam[0][1:]
result = {sno:dict(zip(keys, values)) for sno, *values in spam[1:]}
print(result)

output

{1: {'Name': 'Rome', 'Age': 43, 'Spirit': 'Gemini', 'Status': None}, 2: {'Name': 'Legolas', 'Age': 92, 'Spirit': 'Libra', 'Status': None}}

CodePudding user response:

I'm sure you'd love Pandas. There is a bit of learning curve, but it offers a lot in exchange - most of operations over this dataset can be done in a single line of code.

import pandas as pd
pd.DataFrame(list1[1:], columns=list1[0]).set_index('Sno')

Output:

        Name  Age  Spirit Status
Sno                             
1       Rome   43  Gemini   None
2    Legolas   92   Libra   None

CodePudding user response:

my_dict = {p[0]: dict((x,y) for x, y in zip(list1[0][1:], p[1:])) for p in list1[1:]}
print(my_dict)

Results in:

{1: {'Name': 'Rome', 'Age': 43, 'Spirit': 'Gemini', 'Status': None}, 2: {'Name': 'Legolas', 'Age': 92, 'Spirit': 'Libra', 'Status': None}}
  • Related