3

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!

2 Answers2

1

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),))
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

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),))
I'mahdi
  • 23,382
  • 5
  • 22
  • 30