Python Generate a dynamic dictionary from the list of keys

前端 未结 7 1361
长发绾君心
长发绾君心 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 02:56

    I'm just learning python, so my code could be not very pythonic, but here's my code

    d = {}
    
    keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
    keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
    value1 = "Roger"
    value2 = 3
    
    def insert(cur, list, value):
        if len(list) == 1:
            cur[list[0]] = value
            return
        if not cur.has_key(list[0]):
            cur[list[0]] = {}
        insert(cur[list[0]], list[1:], value)
    
    insert(d, keyList1, value1)
    insert(d, keyList2, value2)
    
    {'Person': {'Male': {'Boy': {'Student': {'id_123': {'Age': 3, 'Name': 'Roger'}}}}}}
    

提交回复
热议问题