Python Generate a dynamic dictionary from the list of keys

前端 未结 7 1359
长发绾君心
长发绾君心 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:06

    >>> mydict = {}
    >>> keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
    >>> value1 = "Roger"
    >>> reduce(lambda x, y: x.setdefault(y, {}), keyList1, mydict)
    {}
    >>> mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value1
    

    You can also do it in one step like this

    >>> keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
    >>> value2 = 25
    >>> reduce(lambda x,y: x.setdefault(y,{}), keyList2[:-1], mydict).update({keyList2[-1]: value2})
    

提交回复
热议问题