Creating a nested dictionary from a flattened dictionary

后端 未结 7 2033
-上瘾入骨i
-上瘾入骨i 2020-12-15 02:43

I have a flattened dictionary which I want to make into a nested one, of the form

flat = {\'X_a_one\': 10,
        \'X_a_two\': 20, 
        \'X_b_one\': 10,         


        
7条回答
  •  借酒劲吻你
    2020-12-15 03:19

    The other answers are cleaner, but since you mentioned recursion we do have other options.

    def nest(d):
        _ = {}
        for k in d:
            i = k.find('_')
            if i == -1:
                _[k] = d[k]
                continue
            s, t = k[:i], k[i+1:]
            if s in _:
                _[s][t] = d[k]
            else:
                _[s] = {t:d[k]}
        return {k:(nest(_[k]) if type(_[k])==type(d) else _[k]) for k in _}
    

提交回复
热议问题