Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions in dictionary comprehension [duplicate]

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?

How to handle exceptions in a list comprehensions?

like image 1000
artemis Avatar asked Dec 10 '22 01:12

artemis


2 Answers

You can test for 0 with an inline if:

lengths[k] / v if v != 0 else 0 directly in the comprehension

like image 73
njzk2 Avatar answered May 19 '23 08:05

njzk2


The last line, you are overwriting the dictionary. Instead append to the dictionary by using the following syntax.

inplace of

cosine_sims = {dot_key:currVal}

use

cosine_sims[dot_key]=currVal 
like image 24
venkata krishnan Avatar answered May 19 '23 06:05

venkata krishnan