如何在字典键上附加一个值

如何在字典键上附加一个值

本文介绍了如何在字典键上附加一个值?(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' 对象没有属性 '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.

这篇关于如何在字典键上附加一个值?(AttributeError:&amp;#39; str&amp;#39;对象没有属性&amp;#39; append&amp;#39;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 14:48