Comparing two dicts in Python

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 try to skip them each and find out which values ​​have spendingmore values ​​in budgets. Currently I wrote:

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 is clearly not the case. Can someone explain my mistake when approaching this?

Thank:)

+4
source share
4 answers

value in spending.values() > budgets.values() value in spending.values() - - budget.values(): budget. Python , - , True. , , :

for key in spending:
    if spending[key] > budgets[key]:
        print('Over Budget')
    else:
        print('Under Budget')

EDIT: Python 2. Python 3 TypeError: unorderable types, , .

+6

dict.items():

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}

for category, spent in spending.items():
    print(category)
    if spent > budgets[category]:
        print('Over Budget')
    else:
        print('Under Budget')
+2

@aryamccarthy , Python , , :

{(sk, 'Over Budget') if sv > budgets[sk] 
       else (sk, 'Under Budget') for sk, sv in spending.items()}

, , , print :

{('Marketing', 'Under Budget'), ('Sales', 'Over Budget'), ('Engineering', 'Over Budget'), ('Operations', 'Over Budget')}

, KeyError spending, budgets.

+1
source

if value in spending.values() > budgets.values(): it should be value in spending.values():

for value in spending.values():
   v={k:v for (k,v) in budgets.items() if v > value}
   if v:
      print "Under"
   else:
      print value, "is spending greater than the values in budget"
0
source

Source: https://habr.com/ru/post/1674395/


All Articles