Search code examples
pythonpython-3.xdictionarynesteddictionary-comprehension

Convert nested lists to dictionary in python


I need to convert the nested list result = [[450, 455, 458], [452, 454, 456, 457], [451, 453]] to a dictionary like:

{
    0: 
         {
             450: None,
             455: 450,
             458: 450
         },
    1:   {
             452: None,
             454: 452,
             456: 452,
             457: 452
         },
    2:   {
             451: None,
             453: 451
         }

}

Please take a look at this and assist:

result_group = {}
for sub_group in result:
    group_count = 0
    first_rel_item = 0
    result_group[group_count] = dict()
    for item in sub_group:
        if item == sub_group[0]:
            result_group[group_count][item] = None
            first_rel_item = item
            continue
        result_group[group_count]['item'] = first_rel_face
        group_count += 1

I messed up with this as i get key Error:1 cant add to dictionary.


Solution

  • Try this:

    result_group = {}
    group_count = 0
    for sub_group in result:
        first_rel_item = 0
        result_group[group_count] = {}
        result_group[group_count][sub_group[0]] = None
        previtem = sub_group[0]
        for item in sub_group[1:]:
            result_group[group_count][item] = previtem
            previtem = item
        group_count += 1