Reputation: 1219
I have been doing some reading and I think the correct solution to what I am trying to achieve is a dictionary...
I have been playing and looking at examples and they seem the way to go. I am having a problem though. While I can create a key and set its value without issues, I am unable to add values to an existing key.
Here is what I am trying
dict = {}
...
if key not in dict:
dict[key] = value
else:
dict[key].append(value)
It gives me...
AttributeError: 'str' object has no attribute 'append'
The if else statement is firing correctly if I use prints. The key is added if it does not exist. The error only occurs on the append line.
What I expect is a list of values per key.
Thanks, Chris
Upvotes: 1
Views: 87
Reputation: 8077
I think you just need to insert your initial key as a list with one element:
dict = {}
...
if key not in dict:
dict[key]=[value]
else:
dict[key].append(value)
this works fine:
dict={}
dict["key"]=[1]
dict["key"].append(2)
dict
{'key': [1, 2]}
Upvotes: 1
Reputation: 920
As mentioned by @kenny
All you have to do is
from collections import defaultdict
dic = defaultdict(list)
# it creates a list if the key is not in dictionary automatically
dic[key].append(value)
Upvotes: 2