gpt4 book ai didi

Python 从键列表生成动态字典

转载 作者:太空狗 更新时间:2023-10-29 20:45:58 25 4
gpt4 key购买 nike

我确实有一个列表,如下所示 -

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

如何生成可按如下方式检索的动态字典 -

mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"] = value

列表可以是任何东西;可变长度或由“N”个我不知道的元素组成...

现在我有了另一个列表,所以我的字典应该相应地更新

keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value2 = 25

即如果键“Person”、“Male”、“Boy”、“Student”、“id_123”已经存在,则应附加新键“age”...

最佳答案

我刚学 python,所以我的代码可能不是很 pythonic,但这是我的代码

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 从键列表生成动态字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com