I have two dictionaries:
length = {1: 3, 2: 9, 3: 1, 4: 1, 5: 0, 6: 0, 7: 5, 8: 0}
result = {1: 3.0, 2: 3.7416573867739413, 3: 7.874007874011811, 4: 6.4031242374328485, 5: 4.0, 6: 0.0, 7: 5.0, 8: 1.0}
When the keys match, I need to divide the result value by the length value. So for example:
Key = 1: 3.0 / 3
Key = 2: 3.7416573867739413 / 9
etc
For all keys in result. I have tried using the following dictionary comprehension:
sims = {k:lengths[k] / v for k, v in result.items()}
But I get an error for ZeroDivisionError: float division by zero
I then tried to avoid comprehension with an ugly code, and use:
for dot_key, dot_val in result.items():
for length_key, length_val in lengths.items():
if dot_key == length_key:
try:
currVal = float(dot_val / length_val)
except ZeroDivisionError:
currVal = 0
cosine_sims = {dot_key:currVal}
print(cosine_sims)
But I only get a result for Key = 8
{8: 0.0}
These SO posts indicate you cannot use Try...Catch
in comprehension, so how can I achieve the desired result by dividing one value by another with the same key in two different dicts?