EN VI

Python - Problems with reciprocal of an dictionary?

2024-03-14 18:00:09
How to Python - Problems with reciprocal of an dictionary

given dict: weights = {"A":16, "B": 3, "C": 5) I want to have the reciprocal of the values.

Output: weights_dict_reci = {"A":0,0625, "B": 0,3333333, "C": 0,2)

So far I tried: weights_dict_reci = {value: 1 / weights_dict[value] for value in weights_dict}

and

for key in weights_dict:
    weights_dict[key] = 1 / weights_dict[key]

Everytime i get the error: unsupported operand type(s) for /: 'int' and 'function'

1st: How to make tke reciprocal for the dict values?

2nd: what is the cause for this error in my code?

Thanks!

Solution:

The following appears to work fine on my version of Python (but you have syntax errors from the start in your question).

weights_dict = {"A":16, "B": 3, "C": 5}
weights_dict_reci = {value: 1 / weights_dict[value] for value in weights_dict}
print( weights_dict )
print( weights_dict_reci )

Output:

{'A': 16, 'B': 3, 'C': 5}
{'A': 0.0625, 'B': 0.3333333333333333, 'C': 0.2}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login