How do I append a value to dict key? (AttributeError: 'str' object has no attribute 'append')

天大地大妈咪最大 提交于 2021-02-08 10:13:58

问题


Say I have a dictionary with one key (and a value):

dict = {'key': '500'}.

Now I want to add a new value '1000' to the same key. However,

dict[key].append('1000')

just gives me "AttributeError: 'str' object has no attribute 'append'".

If I do

dict[key] = '1000' 

it replaces the previous value.

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!


回答1:


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.



来源:https://stackoverflow.com/questions/49437153/how-do-i-append-a-value-to-dict-key-attributeerror-str-object-has-no-attrib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!