TypeError: string indices must be integers, not dict - nested values in dict

TypeError: string indices must be integers, not dict - nested values in dict

我正在尝试在 python 字典中编写包含多个键和值的代码。例如,我的字典将如下所示:

d={"p1": {"d1":{"python":14,"Programming":15}}, "p2": {"d1":{"python":14,"Programming":15}} }

这里我有一个方法可以在特定值不存在时填充字典。 代码如下所示:

我修改了函数以接受 1 个参数。比如我的参数是

这种情况下如何更新字典?

我试过了:

FunDictr(d1)
#say the calling function passed 'foo'
#means d1 = foo

    with io.open("fileo.txt", "r", encoding="utf-8") as filei:
        d = dict()
        for line in filei:
            words = line.strip().split()
            for word in words:
                if word in d:
                    d[d1][word] += 1
                else:
                    d[d1][word] = 1

我期待看到{"foo":{"d1":{"python":14}}

当我写这个的时候,我得到错误:

d[d1][word] += 1
TypeError: string indices must be integers, not dict

根据您提供的示例,您似乎正在寻找类似这样的东西。

def FunDictr(base_dictionary,string_key):
    d = dict()
    d[string_key] = dict()
    d[string_key]["d1"] = dict()
    with io.open("fileo.txt", "r", encoding="utf-8") as filei:   
        for line in filei:
            words = line.strip().split()
            for word in words:
                if word in d[string_key]["d1"]:
                    d[string_key]["d1"][word] += 1
                else:
                    d[string_key]["d1"][word] = 1

这将接受一个初始字典,使用传递给函数的键添加一个新项,使用字符串 d1 的键创建一个嵌套字典作为该键的值,然后在其中创建另一个字典掌握字数。

出于好奇,额外嵌套的目的是什么?为什么不拍。

{'foo':{'python':14}}

此外,我强烈建议使用更具描述性的变量名称。它让生活更轻松:)