-2

I'm trying to do a division operation between two dict and I'm always getting an int result, but I expected a float.

Here is what is going on:

test_dict1 = {'gfg': 20, 'is': 24, 'best': 30}
test_dict2 = {'gfg': 7, 'is': 7, 'best': 7}

res = {key: test_dict1[key] // test_dict2.get(key, 0)
       for key in test_dict1.keys()}

res = {'best': 4, 'gfg': 2, 'is': 3}
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Croyd
  • 39
  • 5
  • 1
    See [// floor division](https://www.pythontutorial.net/advanced-python/python-floor-division/) – Henry Ecker Apr 25 '21 at 00:36
  • Please go through the [intro tour](https://stackoverflow.com/tour), the [help center](https://stackoverflow.com/help) and [how to ask a good question](https://stackoverflow.com/help/how-to-ask) to see how this site works and to help you improve your current and future questions, which can help you get better answers. – Prune Apr 25 '21 at 00:37
  • 1
    Stack Overflow is not intended to replace existing tutorials and documentation. You used integer division; why do you expect something other than the documented return type? – Prune Apr 25 '21 at 00:37
  • 1
    I don't think he knew that `//` was integer division / quotient / floor function... I don't suspect this is a case of malice. That being said, he probably should have looked elsewhere before posting. @prune – Parmandeep Chaddha Apr 25 '21 at 00:41
  • The issue is not malice, but whether the question belongs in the SO archives. The intro tour clearly states the expected research. See [How much research](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) and the [Question Checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Prune Apr 25 '21 at 00:43
  • Does this answer your question? [What is the difference between '/' and '//' when used for division?](https://stackoverflow.com/questions/183853/what-is-the-difference-between-and-when-used-for-division) – SuperStormer Apr 25 '21 at 01:11

1 Answers1

1

There's a problem with your operator: //. The // operator in python returns the quotient from a division. Taking the 'best' key as an example, 30 // 7 => 4Q, 2R. What you are looking for is simply the / operator. 30/7 = 4.285.....

Corrected:

res = {
    key: test_dict1[key] / test_dict2.get(key, 0) for key in test_dict1.keys()
}