Python Generate a dynamic dictionary from the list of keys

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

    Perhaps you could subclass dict:

    class ChainDict(dict):
        def set_key_chain(self, keyList, value):
            t = self
            for k in keyList[:-1]:
                t = t.setdefault(k, {})
            t.setdefault(keyList[-1], value)
    
    c = ChainDict()
    c.set_key_chain(['Person', 'Male', 'Boy', 'Student', 'id_123', 'Name'], 'Roger')
    print c
    >>{'Person': {'Male': {'Boy': {'Student': {'id_123': {'Name': 'Roger'}}}}}}
    
    c.set_key_chain(['Person', 'Male', 'Boy', 'Student', 'id_123', 'Age'], 25)
    print c
    >>{'Person': {'Male': {'Boy': {'Student': {'id_123': {'Age': 25,
          'Name': 'Roger'}}}}}}
    

提交回复
热议问题