How do I unfold python overlaid dict without a flatten external library?

Asked 2 years ago, Updated 2 years ago, 136 views

nested = {'X': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20},
          'Y': {'a': {'one': 10, 'two': 20}, 'b': {'one': 10, 'two': 20}}}

This dict value is

nested = {'X_a_one':10, 'X_a_two':20...}

I'm going to make it flat.

I tried as below, but my head is not working in the middle.

def flat_dict(dup_dict):
    result = {}
    for k, v in dup_dict.items():
        if type(v) is dict:
            for k1, v1 in v.items():
                if type(v1) is dict:
                    key = k+k1
                    value = v1
                for k2, v2 in v1.items():
                    print(k2, v2)
                    print("key:", k+k1+k2, "/value:", v2 )
        else:
            result[k] = v
        # # if type(v) is dict:
        #     #     _flat_dict_rec(k, v, result)
    return

python python3.6 flatten dictionary

2022-09-20 19:19

1 Answers

https://github.com/ianlini/flatten-dict

Please refer to the library code above.


2022-09-20 19:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.