根据N个数组项查找嵌套字典的值

2024-04-25 01:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解决这个问题:我有一个值数组,它可能是字典中的键,也可能不是。然后,如果它们不存在,我想添加它们

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]来更深入地阅读字典,但这让我陷入了困境

感谢您的帮助


Tags: inforif字典ismagic数组this
1条回答
网友
1楼 · 发布于 2024-04-25 01:14:48

这是一个奇怪的练习;有点类似于将元素附加到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作为“当前”变量,这意味着您丢失了对主词典(第一个“节点”)的原始引用

相关问题 更多 >