how to divide between values in inline dictionary

Question:

I have studied here and here, but still fail too.

this is my code:

d1 = {"Overall_Value" : 21600, "Unit_Number": 48}

i just want to divide value in dictionary 21600/48

The output I want is: 450.

Thank you

Any help will be highly appreciated.

Asked By: Fahrizal

||

Answers:

If I am understanding your question correctly you actually do not need to use a dictionary comprhension here, just simple dictionary access and division.

Try this runnable example:

#!/usr/bin/env python

d1 = {"Overall_Value" : 21600, "Unit_Number": 48}
r = d1["Overall_Value"]/d1["Unit_Number"]
print("r=",r)

<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Dictionary comprehensions are used to concisely construct a dictionary using the output of an inline for loop. So if you had a bunch of records and you wanted to convert all of them into a dictionary, then you might use a dictionary comprehension like this…

#!/usr/bin/env python

many_records = [
{"id":"a", "Overall_Value" : 21600, "Unit_Number": 48},
{"id":"b", "Overall_Value" : 2200, "Unit_Number": 24},
]
many_outputs = {d["id"]: d["Overall_Value"]/d["Unit_Number"] for d in many_records}
print("many_outputs=", many_outputs)

<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Answered By: Modularizer
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.