【问题标题】:Python - Add to a dictionary using a stringPython - 使用字符串添加到字典
【发布时间】:2015-02-01 12:01:06
【问题描述】:

[Python 3.4.2]
我知道这个问题听起来很荒谬,但我不知道我在哪里搞砸了。我正在尝试通过使用字符串而不是引用的文本将键和值添加到字典中。所以代替这个,

dict['key'] = value

这个:

dict[key] = value

当我运行上面的命令时,我得到这个错误:

TypeError: 'str' object does not support item assignment  

我认为 Python 认为我正在尝试创建一个字符串,而不是添加到字典中。我猜我使用了错误的语法。这就是我想要做的:

dict[string_for_key][string_for_value] = string_for_deeper_value  

我希望这个 ^ 命令执行此操作:

dict = {string_for_key: string_for_value: string_for_deeper_value}

我收到此错误:

TypeError: 'str' object does not support item assignment  

我可能应该提供更多背景信息。我是:

  1. 创建一本字典
  2. 创建它的副本(因为我需要在遍历字典时编辑字典)
  3. 在运行一些查询时遍历第一个字典
  4. 尝试将查询结果分配为字典中每个“键:值”的值。

这是一张图片来说明我的意思:

键:值:query_as_new_value

-----编辑-----

对不起,我应该澄清一下:字典的名字实际上不是'dict';我在我的问题中称它为“dict”以表明它是一本字典。

-----编辑-----

我将在我的脚本中发布我正在编写的整个过程。该错误发生在函数的最后一个命令期间。在最底部注释掉的是我尝试过的其他一些事情。

from collections import defaultdict

global query_line, pericope_p, pericope_f, pericope_e, pericope_g


def _pre_query(self, typ):
    with open(self) as f:
        i = 1
        for line in f:
            if i == query_line:
                break
            i += 1
        target = repr(line.strip())
    ###skipping some code
    pericope_dict_post[self][typ] = line.strip()
    #^Outputs error TypeError: 'str' object does not support item assignment
    return


pericope_dict_pre = {'pericope-p.txt': 'pericope_p',
                     'pericope-f.txt': 'pericope_f',
                     'pericope-e.txt': 'pericope_e',
                     'pericope-g.txt': 'pericope_g'}
pericope_dict_post = defaultdict(dict)
#pericope_dict_post = defaultdict(list)
#pericope_dict_post = {}
for key, value in pericope_dict_pre.items():
    pericope_dict_post[key] = value
        #^Works
    #pericope_dict_post.update({key: value})
        #^Also works
    #pericope_dict_post.append(key)
        #^AttributeError: 'dict' object has no attribute 'append'
    #pericope_dict_post[key].append(value)
        #^AttributeError: 'dict' object has no attribute 'append'
    _pre_query(key, value)

-----最终编辑-----

Matthias 帮助我解决了这个问题,尽管acushner 也有解决方案。我试图使字典深三个“级别”,但 Python 字典不能以这种方式工作。相反,我需要创建一个嵌套字典。举个例子,当我需要做{key: {key: value}}时,我试图做{key: value: value}

要将它应用到我的代码中,我需要一次创建包含所有三个字符串的 [second] 字典。所以不要这样:

my_dict[key] = value1
my_dict[key][value1] = value2

我需要这样做:

my_dict[key][value1] = value2

非常感谢大家的帮助!

【问题讨论】:

  • 为什么会被否决?
  • 不清楚你想达到什么,你能显示预期的输入和输出
  • 好的,谢谢,我编辑了一下。
  • 如果key没有被定义就会报错
  • 是的,它已经定义好了。所有三个字符串(string_for_keystring_for_valuestring_for_deeper_value)都已定义。字典已经包含string_for_key 指向的键和string_for_key 指向的值。我也在尝试将string_for_deeper_value 插入字典中。

标签: python dictionary


【解决方案1】:

您可以创建一个自行扩展的字典(需要 Python 3)。

class AutoTree(dict):
"""Dictionary with unlimited levels"""

     def __missing__(self, key):
        value = self[key] = type(self)()
        return value

像这样使用它。

data = AutoTree()
data['a']['b'] = 'foo'
print(data)

结果

{'a': {'b': 'foo'}}

现在我将通过消息TypeError: 'str' object does not support item assignment 解释您的问题。

此代码将起作用

from collections import defaultdict
data = defaultdict(dict)
data['a']['b'] = 'c'

data['a'] 不存在,因此使用默认值dict。现在data['a']dict,这个字典得到一个新值,键为'b',值'c'

此代码不起作用

from collections import defaultdict
data = defaultdict(dict)
data['a'] = 'c'
data['a']['b'] = 'c'

data['a'] 的值定义为字符串'c'。现在您只能使用data['a'] 执行字符串操作。您现在不能将它用作字典,这就是 data['a']['b'] = 'c' 失败的原因。

【讨论】:

  • 您甚至不需要为此开设课程。 dd = lambda: defaultdict(dd)
  • @acushner:我赞成你的回答,因为那是我会做的。我的代码只是一个更复杂类的一部分,有时可能会派上用场。
  • AutoTreedd = lambda: defaultdict(dd) 选项仍然给我TypeError: list indices must be integers, not str。感谢大家的帮助。我认为问题在于我在等式右侧使用字符串而不是文本。所以my_dict[key][value] = string 而不是my_dict[key][value] = 'text'
  • 不是这样的。一点也不。 my_dictlistmy_dict[key]list。那是你的问题。
  • @GreenRaccoon23:错误TypeError: list indices must be integers, not str 与字典代码无关。没有涉及列表。
【解决方案2】:

首先,不要使用dict 作为变量名,因为它会影响同名的内置函数。

其次,你想要的只是一个嵌套字典,不是吗?

from collections import defaultdict

d = defaultdict(dict)
d[string_for_key][string_for_value] = 'snth'

正如@Matthias 建议的那样,另一种方法是创建一个无底字典:

dd = lambda: defaultdict(dd)
d = dd()
d[string_for_key][string_for_value] = 'snth'

【讨论】:

  • 谢谢,我试过了,但我用的是d[string_for_key][string_for_value] = snth,而不是d[string_for_key][string_for_value] = 'snth'。它给了我错误TypeError: list indices must be integers, not str
  • 您正在某处创建列表。检查对象的类型
  • 是的,对不起,我的意思是TypeError: 'str' object does not support item assignment。我也在另一条评论中这样做了。 :S
【解决方案3】:

你可以这样做:

>>> my_dict = {}
>>> key = 'a'               # if key is not defined before it will raise NameError
>>> my_dict[key] = [1]
>>> my_dict[key].append(2)
>>> my_dict
{'a': [1, 2]}

注意:dict 是内置的,请勿将其用作变量名

【讨论】:

  • 谢谢,我试过了,但我收到了错误AttributeError: 'dict' object has no attribute 'append'
  • 当然,我在原始问题中添加了一些脚本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-11
  • 2019-09-26
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
相关资源
最近更新 更多