New to Python - is there a straightforward way to iterate over a tuple list and make a calculation using a performance threshold (ie, daily sales % over/under budgeted sales)? Please see the info below:
daily_sales = [('A',150000),('B',73000),('C',110000),('D',231000),('E',66000)]
budgeted_sales = {'A':140000,'B':103000,'C':80000,'D':20000,'E':90000}
performance_threshold = .20
To keep things simple, you can do this in a loop. The first line loops through each tuple pair in daily_sales
. For the first pair, item[1]
is 150000. It then gets item[0]
(ie A) from the dictionary. Note that this will fail if there is no matching item in the dictionary.
for item in daily_sales:
performance = item[1] / float(budgeted_sales.get(item[0])) - 1
if performance > 0:
print "Over {0:.2%}".format(performance)
else:
print "Under {0:.2%}".format(performance)
Over 7.14%
Under -29.13%
Over 37.50%
Over 1055.00%
Under -26.67%
I guess what you are looking for is something like this:
for i in daily_sales:
if i[1] > budgeted_sales['A']:
//Do something
The important bit here is that tuples are immutable, so you access it by referencing a position (eg i[0]). Dict entries can be accessed by referencing their key (eg myDict['myKey']
I Hope this helps!
Since you are new to Python here is an easy way to do that without too complex syntax:
# For each tuple inside daily_sales
for sale in daily_sales:
# Use the first element of that tuple as a key and check if it's inside the dictionary budgeted_sales
if sale[0] in budgeted_sales:
# Compare the value stored for that key with the second element of the tuple (which contains the other price) and print stuff
if budgeted_sales[sale[0]] > sale[1]: print('Over')
else: print('Under')
The check above is optional however it ensures that you don't bluntly access the dictionary with a key that doesn't exists and then try to add a non-existent value with an existent one.
Just because no one mentioned it, you can unpack in the for loop to make the code simpler to understand (including the performance_threshold
):
for day, sales in daily_sales:
performance = float(sales) / budgeted_sales[day]
if performance > 1+performance_threshold:
print "Over {0:.2%}".format(performance)
elif performance < 1-performance_threshold:
print "Under {0:.2%}".format(performance)
else:
print "Target {0:.2%}".format(performance)
Output:
Target 107.14%
Under 70.87%
Over 137.50%
Over 1155.00%
Under 73.33%
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.