Python Generate a dynamic dictionary from the list of keys

前端 未结 7 1373
长发绾君心
长发绾君心 2021-02-09 02:38

I do have a list as given below -

keyList1 = [\"Person\", \"Male\", \"Boy\", \"Student\", \"id_123\", \"Name\"]
value1 = \"Roger\"

How can I ge

7条回答
  •  执念已碎
    2021-02-09 03:00

    You can do this by making nested defaultdicts:

    from collections import defaultdict
    
    def recursive_defaultdict():
        return defaultdict(recursive_defaultdict)
    
    def setpath(d, p, k):
        if len(p) == 1:
            d[p[0]] = k
        else:
            setpath(d[p[0]], p[1:], k)
    
    mydict = recursive_defaultdict()
    
    setpath(mydict, ["Person", "Male", "Boy", "Student", "id_123", "Name"], 'Roger')
    
    print mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"]
    # prints 'Roger'
    

    This has the nice advantage of being able to write

    mydict['a']['b'] = 4
    

    without necessarily having to use the setpath helper.

    You can do it without recursive defaultdicts too:

    def setpath(d, p, k):
        if len(p) == 1:
            d[p[0]] = k
        else:
            setpath(d.setdefault(p[0], {}), p[1:], k)
    

提交回复
热议问题