【发布时间】: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
我可能应该提供更多背景信息。我是:
- 创建一本字典
- 创建它的副本(因为我需要在遍历字典时编辑字典)
- 在运行一些查询时遍历第一个字典
- 尝试将查询结果分配为字典中每个“键:值”的值。
这是一张图片来说明我的意思:
键:值: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_key、string_for_value和string_for_deeper_value)都已定义。字典已经包含string_for_key指向的键和string_for_key指向的值。我也在尝试将string_for_deeper_value插入字典中。
标签: python dictionary