问题
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