0

I'm having a problem looping through dictionaries. I have a nested dictionary structure called dates{} like the following.

('2018-08-21 00:00:00', {'price': 10, 'height': 0.2})
('2018-08-22 00:00:00', {'price': 20, 'height': 0.3})
('2018-08-23 00:00:00', {'price': 30, 'height': 0.4})
.....
....
....

And I need to loop through each date, STARTING AT DATE 20, and calculate the average price of the past 20 days. How would I go about doing this? I tried this:

for key,value in dates.items():
    n = n + 1
    if n >= 20:
    for key,value in dates.items():
        for s in range(n-20,n):
            print(value["price"])

But it won't access the price it'll create some sort of infinite loop, which means I can't work with it!

Thanks

Fidelio
  • 174
  • 12

2 Answers2

1

What you are trying to calculate is called "moving average". See Moving average or running mean for a nice collection of implementations.

First pull the price fields into a separate list, then apply one of the methods you can find on that thread to calculate moving average of length 20.

Cihan
  • 2,267
  • 8
  • 19
0

It's very simple using list comprehension

sum([item['price'] for item in dictionary.values()][:20])/20

If you want to avoid iterating all:

total=0
for item in list(dictionary.values())[:20]:
   total+=item['price']
average=total/20
Sayan Dey
  • 771
  • 6
  • 13