[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
我可能应该提供更多背景信息。我是:
- 创建一本字典
- 创建它的一个副本(因为我需要在遍历它的同时编辑字典)
- 在运行一些查询时迭代第一个字典
- 尝试将查询的结果分配为字典中每个“key: value”的值。
这是一张图片来说明我的意思:
键:值: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
非常感谢大家的帮助!
最佳答案
您可以创建一个自行扩展的字典(需要 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'
失败的原因。
关于Python - 使用字符串添加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279933/