我正在尝试解决这个问题:我有一个值数组,这些值可能是也可能不是字典中的键。如果它们不存在,我想添加它们。
myarr = ['one', 'two', 'three', 'four']
mydict = {'one': {'two': {'three': {}}}}
for item in myarr:
if item in mydict:
(this is where my brain shuts off)
else:
(via some sort of magic)
mydict[insert_magic_here] = {'four': {}}
我尝试使用for i in range(len(myarr)):
自动递增,但这不起作用。我还尝试过使用 mydict = mydict[i]
来更深入地研究字典,但这将我逼入了困境。
感谢任何帮助!
最佳答案
这是一个奇怪的练习;有点类似于将元素附加到 linked list 。通常的解决方案是使用 current
变量来跟踪当前在序列中的位置,并将 current
更新为每次迭代的下一个“节点”。
myarr = ['one', 'two', 'three', 'four']
mydict = {'one': {'two': {'three': {}}}}
current = mydict
for item in myarr:
# insert if not present
if item not in current:
current[item] = dict()
# advance to next
current = current[item]
结果:
>>> mydict
{'one': {'two': {'three': {'four': {}}}}}
您原始解决方案的问题可能是您使用 mydict
作为“当前”变量,这意味着您丢失了对主词典(第一个“节点”)的原始引用。
关于python - 根据 N 个数组项查找嵌套的 Dictionary 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147623/