Anthony
Anthony

Reputation: 39

Add an extra value to a dict key

If have to following dict:

graph = {'A': ['B', 'C'], 'B': ['C', 'D']}

How can i add an extra value to (for example) key a (so the result will be

graph = {'A': ['B', 'C', 'Z'], 'B': ['C', 'D']}

Upvotes: 1

Views: 9855

Answers (2)

girardengo
girardengo

Reputation: 725

Try this, add "Z" element to list:

graph["A"] += "Z"

Upvotes: 2

msvalkon
msvalkon

Reputation: 12077

Your values in the dictionary are lists. Thus the following works:

>>> graph['A'].append('Z')

list.append() adds an item to the end of the list.

Example:

>>> graph = {'A': ['B', 'C'], 'B': ['C', 'D']}
>>> graph['A'].append('Z')
>>> graph
{'A': ['B', 'C', 'Z'], 'B': ['C', 'D']}

Upvotes: 7

Related Questions