【问题标题】:Find nested Dictionary value based on N number of array items根据 N 个数组项查找嵌套字典值
【发布时间】:2019-12-02 22:32:00
【问题描述】:

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

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

感谢任何帮助!

【问题讨论】:

  • 欢迎来到 SO!请显示您的预期输出。我建议使用比myarrmydict 更具描述性的变量名称,这基本上不告诉我它们的用途是什么。
  • 嵌套字典是否总是与myarr中的键顺序相同?
  • 显示您希望在mydict 中添加{'four': {}} 的位置并显示最终预期结果。
  • - 键的顺序总是正确的
  • 最后一个元素会以同样的方式嵌套在前一个元素之下

标签: python python-3.x list dictionary


【解决方案1】:

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

【讨论】:

  • 这正是我所需要的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-02
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2022-10-12
  • 2018-02-27
  • 1970-01-01
相关资源
最近更新 更多