how to Convert Dict ( in which key is in tuple ) to nested Dictionary

Viewed 117

there is a dictionary in which key is a tuple.

{('Feb', 'File1', '100'): {'1': 78, '2': 408, '3': 202, '4': 39},
 ('Feb', 'File1', '101'): {'1': 201, '2': 101, '3': 529, '4': 103},
  ('May', 'File1', '100'): {'1': 78, '2': 402, '3': 20, '4': 39}}

Based on month i need to convert to a nested dict format

how to convert the above dict into this format

{
    "Feb": {
        "File1": {
            "100": {
                "1": 78,
                "2": 408,
                "3": 202,
                "4": 39
            },
            "101": {
                "1": 201,
                "2": 101,
                "3": 529,
                "4": 103
            }}},
    "May": {
        "File1": {
            "100": {
                "1": 78,
                "2": 402,
                "3": 20,
                "157": 39
            }}}
}
2 Answers

The answer to your question is given in the below link if you still have any doubt please revert back.

Creating dynamic nested dictionary of counts

or you can do this:

dict = {('Feb', 'File1', '100'): {'1': 78, '2': 408, '3': 202, '4': 39},
        ('Feb', 'File1', '101'): {'1': 201, '2': 101, '3': 529, '4': 103},
        ('May', 'File1', '100'): {'1': 78, '2': 402, '3': 20, '4': 39}}

new = {}
for u, v, w in dict:
  new.setdefault(u,{}).setdefault(v, {})[w] = dict[(u, v, w)]

I think this solution solve your problem.

raw = {('Feb', 'File1', '100'): {'1': 78, '2': 408, '3': 202, '4': 39},
       ('Feb', 'File1', '101'): {'1': 201, '2': 101, '3': 529, '4': 103},
       ('May', 'File1', '100'): {'1': 78, '2': 402, '3': 20, '4': 39}}

new = {}
for keys in raw.keys():
    new[keys[0]] = {keys[1]: {keys[2]: raw[keys]}}

Regards

Vinicius

Related