1

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

Chris
  • 985
  • 2
  • 7
  • 17
  • 1
    You do this when the dict values are already lists. Consider using defaultdict(list). Or you could have done dict[key] = [value,] in the initial assignment. – Kenny Ostrom Sep 21 '20 at 13:26
  • 1
    just change your initial set to "dict[key] = [value]" – Christian Sloper Sep 21 '20 at 13:28
  • Does this answer your question? [list to dictionary conversion with multiple values per key?](https://stackoverflow.com/questions/5378231/list-to-dictionary-conversion-with-multiple-values-per-key) – ClimateUnboxed Sep 21 '20 at 14:09

2 Answers2

2

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)
dbokers
  • 840
  • 1
  • 10
  • 12
1

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]}
ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86