Two python lists to nested dictionaries repeating pattern

Advertisements

I am trying to transform two lists of equal length which contain key:value pairs into nested dictionaries.

List look like

list1 = ['first_name', 'surname', 'BoB', 'Question_no', 'comment1', 'comment2',  'Question_no', 'comment1', 'comment2']

list2 = ['John', 'Smith', 10/10/1980, 'Q1', 'some text', 'other text', 'Q2', 'different text', 'more text']

Current code

for key in name_list:
    for value in values_list:
        data[key] = value
        values_list.remove(value)
        break  

Current output is a single dictionary

{'first_name':'John', 'surname':'Smith', 'BoB':10/10/1980, 'Question_no':'Q1', 'comment1':'some text', 'comment2':'other text',  'Question_no':'Q2', 'comment1':'different text', 'comment2':'more text'}

The output I am look for is to have the repeating parts in their own structure.

{
'details' : {'first_name':'John', 'surname':'Smith', 'BoB':10/10/1980}, 
001 : {'Question_no':'Q1', 'comment1':'some text', 'comment2':'other text'}, 
002 : {'Question_no':'Q2', 'comment1':'different text', 'comment2':'more text'}
}

There will be a differing number of Questions in each.

Many thanks

>Solution :

Some things that should change in the given approach

  1. You don’t need to use nested for loops for building the dictionary. Instead, you need to iterate over the lists at the same time because the elements at position i correspond to each other.
  2. Building the dictionary only through data[key] = value will not create a nested one. You need to specify it like data[outer_key][inner_key] = value or data[outer_key] = {'first_name': 'John'}.

Please see the code below to understand how you can address these.

from collections import defaultdict

data = defaultdict(dict)

def get_outer_key(previous_outer_key):
    if previous_outer_key == 'details':
        return 1
    return previous_outer_key + 1

outer_key = 'details'

name_list = ['first_name', 'surname', 'BoB', 'Question_no', 'comment1', 'comment2',  'Question_no', 'comment1', 'comment2']

values_list = ['John', 'Smith', '10/10/1980', 'Q1', 'some text', 'other text', 'Q2', 'different text', 'more text']

for i, key in enumerate(name_list):
    if key == 'Question_no':
        outer_key = get_outer_key(outer_key)
    value = values_list[i]
    data[outer_key][key] = value

Leave a ReplyCancel reply