Flatten nested dictionaries, compressing keys

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

    I actually wrote a package called cherrypicker recently to deal with this exact sort of thing since I had to do it so often!

    I think the following code would give you exactly what you're after:

    from cherrypicker import CherryPicker
    
    dct = {
        'a': 1,
        'c': {
            'a': 2,
            'b': {
                'x': 5,
                'y' : 10
            }
        },
        'd': [1, 2, 3]
    }
    
    picker = CherryPicker(dct)
    picker.flatten().get()
    

    You can install the package with:

    pip install cherrypicker
    

    ...and there's more docs and guidance at https://cherrypicker.readthedocs.io.

    Other methods may be faster, but the priority of this package is to make such tasks easy. If you do have a large list of objects to flatten though, you can also tell CherryPicker to use parallel processing to speed things up.

提交回复
热议问题