【问题标题】:To insert multiple dictionaries as values into a single key将多个字典作为值插入到单个键中
【发布时间】:2015-09-26 00:12:14
【问题描述】:

我需要一组 {a:{}{b:{},{c:{}}}} 形式的嵌套字典,其中 a、b 和 c 是键。我试过下面的代码。

from collections import defaultdict
def dictizeString(string,dictionary) :
    while string.startswith('/'):
        string = string[1:]
    parts = string.split('/',1)

    if len(parts)>1:
        branch = dictionary.setdefault(parts[0],[dict()])
        dictionary[parts[0]].append(dict())
        dictizeString(parts[1], branch)
    else:
        if dictionary.has_key(parts[0]):
            dictionary[parts[0]]=dict()
        else:
            dictionary[parts[0]]=[dict()]
            dictionary[parts[0]].append(dict())               


d={}

dictizeString('/a/b/c/d', d)
print d

执行此代码会导致错误“list”对象没有属性“setdefault”。该代码适用于第一次迭代(即 a),但在第二次迭代(即 b)时抛出上述错误。

附加功能适用于代码最后 6 行中的 else 部分。我尝试在 if 情况下使用相同的逻辑,但它会引发错误。

【问题讨论】:

  • 打印 d 时您希望输出的样子如何?
  • @dopstar 我希望它在 print d 上是这样的 {a:{}{b:{},{c:{}}}}。 Joshua 对我的代码所做的微小改动正是我所需要的。

标签: python dictionary nested


【解决方案1】:

尝试:

from collections import defaultdict
def dictizeString(string,dictionary) :
    while string.startswith('/'):
        string = string[1:]
    parts = string.split('/',1)

    if len(parts)>1:
        branch = dictionary.setdefault(parts[0],[dict()])
        dictionary[parts[0]].append(dict())
        dictizeString(parts[1], branch[1]) # <--- branch -> branch[1]
    else:
        if dictionary.has_key(parts[0]):
            dictionary[parts[0]]=dict()
        else:
            dictionary[parts[0]]=[dict()]
            dictionary[parts[0]].append(dict())               


d={}

dictizeString('/a/b/c/d', d)
print d

您在第 7 行有一个语句,将默认设置为字典的 list,但随后您尝试坚持使用它期望字典的函数。

【讨论】:

  • 完美!!正是我想要的。我确实花了一些时间才意识到 .setdefault 的返回值是一个键值对。
  • 很高兴提供帮助,但我最初错了,它不返回 对。您只是创建一个列表作为值并附加到它。
  • 有没有一种有效的方法来使用这个嵌套字典中的键访问值?或者是通过破坏目录结构的递归。 a/b/c/d as dict[a][b][c][d] 怎么走?
  • dict[a][b][c][d] 是要走的路。如果我理解正确,python 中确实没有你想要的行为机制,但不要害怕!您需要在字典中递归的最多是 log n 其中 n 是字典中的文件数,因此您的总运行时复杂度是 O(log n) (假设 O(1) 字典查找)仍然是非常好。
【解决方案2】:

我知道你已经找到了答案,但你也可以这样做:

def dictizeString(path, dictionary):
    keys = path.lstrip('/').split('/')
    current_key = None
    for key in keys:
        if current_key is None:
            current_key = dictionary.setdefault(key, {})
        else:
            current_key = current_key.setdefault(key, {})

d = {}
dictizeString('/a/b/c/d', d)
print d

输出变为:{'a': {'b': {'c': {'d': {}}}}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2019-06-03
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    相关资源
    最近更新 更多