Home > OS >  Complex dictionary construction
Complex dictionary construction

Time:06-15

What I have is a list of lists, where are sub-lists are the same size. Like shown below.

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

What I am looking for.

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

1,2, ... are unique (correspond to Sno number)

My progress so far,

I am able to get every second element as the key,

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

print(list1_as_dict)

Output:

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

Not sure on how to proceed further, please assist.

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