Home > Mobile >  Nested dictionary to nested tuple
Nested dictionary to nested tuple

Time:10-25

I know that it shouldn't be hard, however, I can't resolve my issue.

I have a nested dictionary and I need to convert its values to the same structure tuple.

dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}}

The result should be like:

list1 = (32, 7, ((600, 500)))

Do you have any suggestions how to do that?

Thank you!

CodePudding user response:

Try:

dict1 = {"234": 32, "345": 7, "123": {"asd": {"pert": 600, "sad": 500}}}


def get_values(o):
    out = []
    for k, v in o.items():
        if not isinstance(v, dict):
            out.append(v)
        else:
            out.append(get_values(v))
    return tuple(out)


print(get_values(dict1))

Prints:

(32, 7, ((600, 500),))

CodePudding user response:

You can write a recursive function.

dict1 = {'234':32,'345':7,'123':{'asd':{'pert': 600, 'sad':500}}}

def dfs_dct(dct):
    tpl = ()
    for k,v in dct.items():
        if isinstance(v, dict):
            tpl  = (dfs_dct(v),)
        else:
            tpl  = (v,)
    return tpl
res = dfs_dct(dict1)
print(res)

Output:

(32, 7, ((600, 500),))
  • Related