Flatten nested dictionaries, compressing keys

前端 未结 28 2657
遇见更好的自我
遇见更好的自我 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:28

    If you're using pandas there is a function hidden in pandas.io.json._normalize1 called nested_to_record which does this exactly.

    from pandas.io.json._normalize import nested_to_record    
    
    flat = nested_to_record(my_dict, sep='_')
    

    1 In pandas versions 0.24.x and older use pandas.io.json.normalize (without the _)

提交回复
热议问题