2

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
            }}}
}
sri
  • 21
  • 3

2 Answers2

0

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)]
0

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

  • this is the output for ur solution --- {'Feb': {'File1': {'101': {'1': 201, '2': 101, '3': 529, '4': 103}}}, 'May': {'File1': {'100': {'1': 78, '2': 402, '3': 20, '4': 39}}}} .. but for feb month in file1 i have 2 ids ( 100 , 101) . in this output for id 100 values are missing – sri Jul 03 '20 at 06:55