HelloThere
HelloThere

Reputation: 3

Adding multiple values to a key in dictionary

For example I have a dictionary:

dictionary = {'dog' : 'bark', 'cat' : 'kitten'}  

And I want to add another value 'woof' to the key 'dog' so that I get:

{'dog': ['bark','woof'], 'cat' : 'kitten'}  

And then add another value 'speak' to the key 'dog' so that I get:

{'dog': ['bark','woof', 'speak'], 'cat' : 'kitten'}

etc.

Any help is appreciated.

Upvotes: 0

Views: 72

Answers (3)

Matt Eding
Matt Eding

Reputation: 1002

I would implement a defaultdict from the collections module.

Here is an example from the official docs:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Upvotes: 0

Erick Shepherd
Erick Shepherd

Reputation: 1443

You first need to convert the values associated with each key in your dict to lists: You can accomplish this via dict comprehension. Afterwards, it's simply a matter of appending items to the list at the desired key in the dictionary. The following code would work:

dictionary = {"dog" : "bark", "cat" : "kitten"}
dictionary = {key : [value] for key, value in dictionary.items()}

dictionary["dog"].append("woof")
dictionary["dog"].append("speak")

At which point, if you print dictionary, the output will be:

{'dog': ['bark', 'woof', 'speak'], 'cat': ['kitten']}

Upvotes: 3

abeoliver
abeoliver

Reputation: 187

As far as I can tell, the solution is to initialize each dictionary value as a list from the start. For example, initialize your dictionary as dictionary = {'dog' : ['bark'], 'cat' : ['kitten']}. Then, when you want to add new values to your dictionary keys you can use dictionary["dog"].append("speak").

Upvotes: 1

Related Questions