Skip to content
Advertisement

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?

Advertisement

Answer

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}}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement