0

So I am trying to combine two dictionaries with two similar keys. I read the post here in stack overflow about merging two dictionaries. However, when I ran it. It gives me an error of KeyError, even though I have all the keys in both dictionaries.

Here is the code:

coordinates={'hello': (2, 6), 'hola': (2, 6), 'hella': (2, 6), 'heya': (2, 6), 'heyo': (2, 6), 'hill': (2, 6), 'halo': (2, 6), 'hall': (2, 6), 'hail': (2, 6), 'hay': (2, 6), 'hale': (2, 6), 'holy': (2, 6)}

solution={'hello': 'right', 'hall': 'right', 'hella': 'left', 'hale': 'left', 'hail': 'down', 'heya': 'down', 'holy': 'down', 'hola': 'up', 'hay': 'down-right', 'hill': 'up-left', 'heyo': 'up-right', 'halo': 'down-left'}

FINAL_SOL = [coordinates, solution]
FINAL_DICT = {}
for word in coordinates.keys():
  FINAL_DICT[word] = tuple(FINAL_DICT[word] for d in FINAL_SOL)

print(FINAL_DICT)

I was hoping to have a single dictionary with this format:

'Key': (x,y), direction

Please do help in what is making this error. Thanks!

Monsi
  • 43
  • 5
  • Please tell us what is your error and your output, otherwise it's difficult to understand your problem without executing your code – dooms Sep 25 '19 at 16:17
  • Possible duplicate of [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression) – zimbu668 Sep 25 '19 at 17:34

1 Answers1

2

Pretty sure you meant this:

FINAL_DICT[word] = tuple(d[word] for d in FINAL_SOL)

Not:

FINAL_DICT[word] = tuple(FINAL_DICT[word] for d in FINAL_SOL)

Because this way (the way it's written now) will give you a KeyError, since FINAL_DICT is empty initially, and definitely does not have any of the keys that the other dictionaries do.

Paul M.
  • 10,481
  • 2
  • 9
  • 15