Problems with reciprocal of an dictionary

Question:

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!

Asked By: hadji

||

Answers:

In your Minimum Reproducible Example your dictionary is weights.

You can try:

weights = {"A":16, "B": 3, "C": 5}

{k:1/v for k,v in weights.items()}

Alternatively, as you tried in your attempt:

{value: 1 / weights[value] for value in weights}  # here value is the `key` for the dictionary `weights`. 

output

#{'A': 0.0625, 'B': 0.3333333333333333, 'C': 0.2}

I am not sure about weights_dict as you have not provided any information about it.

From the error, it looks like weights_dict[value] is a function somewhere in your code.

Answered By: Palestine

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}
Answered By: lastchance
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.