Ger Cas
Ger Cas

Reputation: 2298

Convert dictionaries inside into list in nested dictionary

I have a dictionary like this

{'C': 
    {
    'G': 
        {
            'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]
        }   
    }
}

and I'm trying to convert to list each value that is a dictionary in order to get a new dictionary like this

{'C': 
    [{
    'G': 
        [{
            'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]
        }]  
    }]
}

To see it easely would be pass from dict1 to dict2

enter image description here

My attempt so far is like this. Thanks in advance.

>>> for k, v in d1.items():
...     if isinstance(v, dict):
...         d1[k,v] = d1[k,[v]]
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: unhashable type: 'list'

Upvotes: 1

Views: 66

Answers (6)

LMC
LMC

Reputation: 12692

Yet another recursion solution (added a third level)

def toList(d, d2):
    for k, v in d.items():
        if isinstance(v, dict):
            d2[k] = [v]
            toList(v, d2[k][0])

d1 = {'C':
    {
    'G':
        {
            'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}],
             "thirdLvl": {'K': '7', 'B': '9'}
        }
    }
}


d2 = {}

toList(d1,d2)
print(d2)

Result:

{'C': 
     [{'G': 
           [{'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}],
             'thirdLvl': [{'K': '7', 'B': '9'}]
            }
           ]
      }
     ]
}

Upvotes: 1

Rikai
Rikai

Reputation: 13

I would use recursion, this seemed to work for me:

main = {
    'C': {
        'G': {
            'Z': '4',
            'L': '1',
            'P': [{'K': '3', 'B': '1'},
                  {'K': '7', 'B': '9'}]
            }
        }
}


def convert_dictionary(dictionary: dict):
    for key, value in dictionary.items():
        if isinstance(value, dict):
            convert_dictionary(value)
            dictionary[key] = [value]


convert_dictionary(main)
print(main)

Tell me if it helped!

Upvotes: 1

cards
cards

Reputation: 4975

Recursive approach

d = {'C':
    {
    'G':
        {
            'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]
        }
    }
}

def d2l(d):
    for k, v in d.items():
        if isinstance(v, dict):
            d2l(v)
            d[k] = [v]

    return d

new_dict = d2l(d)
print(new_dict)

Output

{'C': [{'G': [{'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]}]}]}

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195448

You can try recursion:

dct = {
    "C": {
        "G": {
            "Z": "4",
            "L": "1",
            "P": [{"K": "3", "B": "1"}, {"K": "7", "B": "9"}],
        }
    }
}


def convert(d):
    if isinstance(d, dict):
        out = {}
        for k, v in d.items():
            out[k] = [convert(v)] if isinstance(v, dict) else convert(v)
        return out
    elif isinstance(d, list):
        return [convert(v) for v in d]
    return d


print(convert(dct))

Prints:

{
    "C": [
        {
            "G": [
                {
                    "Z": "4",
                    "L": "1",
                    "P": [{"K": "3", "B": "1"}, {"K": "7", "B": "9"}],
                }
            ]
        }
    ]
}

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can use recursion:

def to_list(d):
   if not isinstance(d, (dict, list)):
      return d
   if isinstance(d, list):
      return list(map(to_list, d))
   return {a:to_list(b) if not isinstance(b, dict) else [to_list(b)] for a, b in d.items()}

vals = {'C': {'G': {'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]}}}
r = to_list(vals)

Output:

{'C': [{'G': [{'Z': '4', 'L': '1', 'P': [{'K': '3', 'B': '1'}, {'K': '7', 'B': '9'}]}]}]}

Upvotes: 2

Sam
Sam

Reputation: 1415

If you want your key to be k then you don't want d1[k,v], rather you should set d1[k] = [v]

Note that you have not provided a way to go deeper into the dictionary, this will only convert top-level values that are dicts to lists containing the dict. You'll need a way to recurse into those dicts if you wish to convert any dicts that they contain as values.

Upvotes: 1

Related Questions