Home > Enterprise >  how to add list value to dictionary to key if the key is already exists
how to add list value to dictionary to key if the key is already exists

Time:06-14

I have a dictionary of all possible words(the keys) and its coordinates on a boggle game board(values).

I am writing a code in order to find all paths of a legal words on the board.

I created a new dictionary in order to contain only the legal words and path, so I want if there is a word with a couple paths I want to combine its to the same value of the word.

At first I a appending the first legal path so for example I have -

{"dog" : [(0,1),(0,2),(0,3)]}

now I have another path - [(1,0),(2,0),(3,0)] and I want the output to be-

{"dog" : [(0,1),(0,2),(0,3)],[(1,0),(2,0),(3,0)]}

I tried a few options but in all of them I get -

{"dog" : [(0,1),(0,2),(0,3),(1,0),(2,0),(3,0)]}

and it is not what I want. I would be happy for any help.

CodePudding user response:

You'll need to start with either an empty list or a list of lists, then append.

dictionary = {"dog" : []}
dictionary['dog'].append([(0,1),(0,2),(0,3)])
dictionary['dog'].append([(1,0),(2,0),(3,0)])

result:

{'dog': [[(0, 1), (0, 2), (0, 3)], [(1, 0), (2, 0), (3, 0)]]}

CodePudding user response:

A key can only hold one value. Your desire output is 2 values for one key. I think a nested array is what you want, it would look like this:

dict = {"dog" : [[(0,1),(0,2),(0,3)]]}
print("Initial dog paths: {}".format(dict["dog"]))

dict["dog"].append([(1,0),(2,0),(3,0)])
print("Final dog paths: {}".format(dict["dog"]))

output:

Initial dog paths: [[(0, 1), (0, 2), (0, 3)]]
Final dog paths: [[(0, 1), (0, 2), (0, 3)], [(1, 0), (2, 0), (3, 0)]]

CodePudding user response:

Dictionary can only have one value for each key. If you want to store multiple values, in this case, lists, you may try a list of list like:

{"dog" : [[(0,1),(0,2),(0,3)]]}

In such case, you can just append the path [(1,0),(2,0),(3,0)] to the outer list and the dictionary will become:

{"dog" : [[(0,1),(0,2),(0,3)],[(1,0),(2,0),(3,0)]]}

Hope this helps!

  • Related