Flatten nested dictionaries, compressing keys

前端 未结 28 2234
遇见更好的自我
遇见更好的自我 2020-11-22 01:16

Suppose you have a dictionary like:

{\'a\': 1,
 \'c\': {\'a\': 2,
       \'b\': {\'x\': 5,
             \'y\' : 10}},
 \'d\': [1, 2, 3]}

Ho

28条回答
  •  旧巷少年郎
    2020-11-22 01:42

    Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator.

    def flatten_json(json):
        if type(json) == dict:
            for k, v in list(json.items()):
                if type(v) == dict:
                    flatten_json(v)
                    json.pop(k)
                    for k2, v2 in v.items():
                        json[k+"."+k2] = v2
    

    Example:

    d = {'a': {'b': 'c'}}                   
    flatten_json(d)
    print(d)
    unflatten_json(d)
    print(d)
    

    Output:

    {'a.b': 'c'}
    {'a': {'b': 'c'}}
    

    I published this code here along with the matching unflatten_json function.

提交回复
热议问题