How do I append a value to dict key? (AttributeError: #39;str#39; object has no attribute #39;append#39;)(如何将值附加到 dict 键?(AttributeError:str对象没有属性append))
问题描述
假设我有一本带有一个键(和一个值)的字典:
Say I have a dictionary with one key (and a value):
dict = {'key': '500'}.
现在我想向同一个键添加一个新值 '1000'.然而,
Now I want to add a new value '1000' to the same key. However,
dict[key].append('1000')
只给我 AttributeError: 'str' object has no attribute 'append'".
如果我这样做了
dict[key] = '1000'
它替换了之前的值.
我猜我必须创建一个列表作为值,并以某种方式将该列表附加为键的值,但我不确定我将如何处理.感谢您的帮助!
I'm guessing I have to create a list as a value and somehow append that list as the key's value but I'm not sure how I would go about this. Thanks for any help!
推荐答案
我建议使用 defaultdict 在缺少键时实例化一个空列表.
I suggest the usage of a defaultdict that instantiates an empty list when a key is missing.
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['key'].append(500)
>>> d
defaultdict(<type 'list'>, {'key': [500]})
>>> d['key'].append(1000)
>>> d
defaultdict(<type 'list'>, {'key': [500, 1000]})
我不建议将字符串/整数作为值,然后在您想附加到字段时切换到列表.保持一致.
I don't recommend having strings/integers as values and then switching to lists once you want to append to a field. Keep it consistent.
这篇关于如何将值附加到 dict 键?(AttributeError:'str'对象没有属性'append')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将值附加到 dict 键?(AttributeError:'str'对象没有属性'append')
基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
