Python从键列表中生成动态字典 [英] Python Generate a dynamic dictionary from the list of keys
本文介绍了Python从键列表中生成动态字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我确实有一个列表如下:
I do have a list as given below -
keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
value1 = "Roger"
如何生成可以如下检索的动态字典 -
How can I generate dynamic dictionary which can be retrieved as below -
mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value
列表可以是任何东西;可变长度或由我未知的N个元素组成...
The list could be anything; Variable Length or consisting of "N" number of elements unknown to me...
现在我有另一个列表,所以我的字典应该相应更新
Now I do have another list, so that My dictionary should be updated accordingly
keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value2 = 25
ie如果键Person,Male,Boy,Student,id_123已经存在,则应该添加新密钥age...
i.e. If Keys "Person", "Male", "Boy", "Student", "id_123" already exists, the new key "age" should be appended ...
推荐答案
我只是学习python,所以我的代码可能不是很pythonic,但是这里是我的代码
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'}}}}}}
这篇关于Python从键列表中生成动态字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文