简体   繁体   中英

How to combine a list of lists into a dictionary where the first sublist is mapped to corresponding values in all subsequent sublists?

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?

Something like

spam = [["Sno","Name","Age","Spirit","Status"],[1, "Rome", 43,"Gemini",None],[2,"Legolas", 92, "Libra",None]]
keys = spam[0][1:] # get the keys from first sub-list, excluding element at index 0

# use dict comprehension to create the desired result by iterating over
# sub-lists, unpacking sno and rest of the values
# zip keys and values and create a dict and sno:dict pair respectively
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}}

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
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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM