简体   繁体   中英

Look-Back Looping through nested dictionaries in Python starting at specific index

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

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM