0

I have a list of dictionaries as input :

[{
Acc: "ABC IN."
CFC: "XC"
CC: "1001"
SC: "DER"
Config Path: "..//"
File Path: "..//"
}]

I wanted to convert it into a template nested dictionary the only catch being the key of the nested dictionary is also derived from the above dictionary itself Desired output

{'XC': {'1001': {'DER': {'Config Path': '..//' ,'File Path' : "..//" }}}}

The input can be multiple and whenever a new CFC , CC or SC arrives a new key is generated on the same level as that of the previous .

I tried dynamically generating key but it was showing key not found error

main_dict = {}
for item in main_dict_list:
    main_dict[item['CFC']][item['CC']][item['SC']]['Config Path']=item['Config Path']
    main_dict[item['CFC']][item['CC']][item['SC']]['File Path']=item['File Path']

I also tried to follow hierarchy to input key-value from inside the dictionary

main_dict = {}


for item in main_dict_list:
 
    temp={}
    temp['model_config_path']=item['Config Path']
    temp['model_config_path']=item['File Path']
    temp1 = {}
    temp1[item['SC']] = temp
    temp2 ={}
    temp2[item['CC']] =temp1
    main_dict[item['CFC']] =temp2

it also doesn't seem to work properly. I am not able to think about any other solution

2 Answers 2

1

You have to create each level.

main_dict = {}
for item in main_dict_list:
    main_dict[item['CFC']] = {item['CC']: {item['SC']: {'Config Path': item['Config Path'], 'File Path': item['File Path']}}}
Sign up to request clarification or add additional context in comments.

2 Comments

the above code seems to over write if any new entry / key is added to a level - not working as supposed to
You didn't specify that as a requirement. Perhaps you need to expand your example.
0

You can use setdefault to auto-merge common keys:

main_dict_list = [
     { 'Acc': "ABC IN.",
       'CFC': "XC",
       'CC': "1001",
       'SC': "DER",
       'Config Path': "..//",
       'File Path': "..//"
     },
     { 'Acc': "ABC IN.",
       'CFC': "XC",
       'CC': "1002",
       'SC': "DER",
       'Config Path': "..//c",
       'File Path': "..//f"
     },
]

main_dict = dict()

for d in main_dict_list:
    content = {k:d[k] for k in ("Config Path","File Path") }
    main_dict.setdefault(d["CFC"],dict()) \
             .setdefault(d["CC"],dict())  \
             .setdefault(d["SC"],content)

print(main_dict)
      
{'XC': {'1001': {'DER': {'Config Path': '..//', 'File Path': '..//'}},
        '1002': {'DER': {'Config Path': '..//c', 'File Path': '..//f'}}}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.