python - 根据 N 个数组项查找嵌套的 Dictionary 值

标签 python python-3.x list dictionary

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

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/

相关文章:

python - 在pycharm的python控制台或终端中设置字体大小

c# - 在 C# 中更新列表

c# - 如何使用 Linq 在列表中查找两个连续项目的子列表

python - 无法将 PyQT 设计器文件编译为 Python

Python BeautifulSoup 只是读取第一行

python - python中的str性能

python - 在 Turtle 模块中使用 PNG

Python 相当于 'grep -C N' ?

Python-Django-Heroku-导入错误-无法从 'fromshare' 导入名称 'socket'

python - 在列表中搜索字母