Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested dictionary to nested tuple

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!

like image 548
Дмитрий Кожин Avatar asked Sep 10 '26 04:09

Дмитрий Кожин


2 Answers

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),))
like image 168
Andrej Kesely Avatar answered Sep 11 '26 18:09

Andrej Kesely


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),))
like image 41
I'mahdi Avatar answered Sep 11 '26 18:09

I'mahdi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!