newbe
newbe

Reputation: 177

Calculating percentage based on python dictionaries

I need help calculating each dict of dict date values to percentage.

raw_data = [{'name':'AB', 'date':datetime.date(2012, 10, 2), 'price': 23.80}, {'name':'AB', 'date':datetime.date(2012, 10, 3), 'price': 23.72}]

i have formarted above dictionary to below format using collection.

import collections
res = collections.defaultdict(dict)

for row in raw_data:
  row_col = res[row['name']]
  row_col[row['date']] = row['price']


  {'AB': {datetime.date(2012, 10, 2): 23.80,
  datetime.date(2012, 10, 3): 23.72,
  datetime.date(2012, 10, 4): 25.90,
  datetime.date(2012, 10, 5): 29.95}

Now i need to calculate above data into below format.

Calculation formula :

last price will dividend for all the top values

   Date                               Price   Percentage 
   datetime.date(2012, 10, 5)         29.95      26%     
   datetime.date(2012, 10, 4)         25.90      9%        
   datetime.date(2012, 10, 3)         23.72      0%      
   datetime.date(2012, 10, 2)         23.80      0       

calculation goes like this

(23.72/23.80-1) * 100 = 0% 
(25.90/23.80-1) * 100 = 9% 
(29.95/23.80-1) * 100 = 26%

Any help really appreciate it.

Upvotes: 1

Views: 2697

Answers (2)

Kevin
Kevin

Reputation: 76194

import datetime
import collections

raw_data = [
{'name':'AB', 'date':datetime.date(2012, 10, 2), 'price': 23.80}, 
{'name':'AB', 'date':datetime.date(2012, 10, 3), 'price': 23.72},
{'name':'AB', 'date':datetime.date(2012, 10, 4), 'price': 25.90},
{'name':'AB', 'date':datetime.date(2012, 10, 5), 'price': 29.95}
]

#all unique names in raw_data
names = set(row["name"] for row in raw_data)
#lowest prices, keyed by name
lowestPrices = {name: min(row["price"] for row in raw_data) for name in names}

for row in raw_data:
    name = row["name"]
    lowestPrice = lowestPrices[name]
    price = row["price"]
    percentage = ((price/lowestPrice)-1)*100
    row["percentage"] = percentage

print raw_data

Output (newlines added by me):

[
{'date': datetime.date(2012, 10, 5), 'price': 29.95, 'percentage': 26.264755480607093, 'name': 'AB'},
{'date': datetime.date(2012, 10, 4), 'price': 25.9, 'percentage': 9.190556492411472, 'name': 'AB'}, 
{'date': datetime.date(2012, 10, 2), 'price': 23.8, 'percentage': 0.337268128161905, 'name': 'AB'}, 
{'date': datetime.date(2012, 10, 3), 'price': 23.72, 'percentage': 0, 'name': 'AB'} 
]

Upvotes: 0

c1phr
c1phr

Reputation: 590

You can grab a list of all the values in your dictionary with something like value_list = res.values(). This will be iterable, and you can grab your price values with a for loop and list slicing. value_list[0] will then contain your lowest price that you're dividing everything by. Then depending on what you plan on doing with the data, you can use a for loop to calculate all the percentages or wrap it in a function and run it as needed.

Referenced: Python: Index a Dictionary?

Upvotes: 1

Related Questions