I have 2 dictionaries:
budgets = {'Engineering': 4500.0,
'Marketing': 5000.0,
'Operations': 3000.0,
'Sales': 2000.0}
spending = {'Engineering': 5020.0,
'Marketing': 1550.0,
'Operations': 3670.0,
'Sales': 3320.0}
I'm trying to loop through them each and find out which values in spending
are greater than the values in budgets
. I currently have written:
for value in spending.values():
if value in spending.values() > budgets.values():
print 'Over Budget'
else:
print 'Under Budget'
However when I run this, they all print Over Budget
which clearly isn't the case. Can someone please explain my error in approaching this?
Thanks :)
The section value in spending.values() > budgets.values()
actually evaluates the boolean query value in spending.values()
--a membership check--then compares the result of that to budget.values()
: the values from budget
. In Python, everything can be compared, so you compare the boolean to the list--the same thing every time, which in your case evaluates to True
. What you'd want is more like this:
for key in spending:
if spending[key] > budgets[key]:
print('Over Budget')
else:
print('Under Budget')
EDIT: This pertains to Python 2 only. In Python 3, you get TypeError: unorderable types
, which keeps you safe from mistakes like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With