user7691120
user7691120

Reputation:

Python looping thru dictionary to access item by index

I was having some problem when trying to sort for dates to be grouped by month in Python. Here is my code:

data_dict =  dict()
for yhat in forecast:
    inverted = inverse_difference(history, yhat, days_in_year)
    #print('Day %d: %f' % (day, inverted))
    data_dict[day] = inverted
    day += 1

# group all the forecasted data by month
default_month = (lambda: data_dict)
month_groups = defaultdict(default_month)
year = 2017
for day, value in data_dict.items():
    month = datetime.strptime('{:0>3}-{}'.format(day, year), '%j-%Y').month
    month_groups[month] = month_groups.values()[month] + value

for key, value in month_groups.items():
    print(key)
    print(value)

Some sample inputs:

Day 1: -109.743833
Day 2: -59.743030
Day 3: -149.539798
Day 4: -134.004097
Day 5: -101.911757
Day 6: -64.655886
Day 7: 38.683420
Day 8: 14.493554
Day 9: -52.823889
Day 10: -16.754896
Day 11: 27.648000
Day 12: -8.978296
Day 13: 3.077756
Day 14: 8.925626
Day 15: -13.099969
Day 16: 36.508620
Day 17: -20.888302
Day 18: 2.014708
Day 19: 52.070549
Day 20: 14.389047
Day 21: 46.281278
Day 22: 6.589799
Day 23: 14.849905
Day 24: 21.924614
Day 25: -19.006338
Day 26: -16.249006
Day 27: 41.147836
Day 28: 25.397426
Day 29: 45.358489
Day 30: 129.366465
Day 31: 129.377892
Day 32: -16.628081
Day 33: 56.484472
Day 34: 73.509385
Day 35: 119.484387
Day 36: -21.506795
Day 37: -16.499800
Day 38: -17.491308
Day 39: 140.532548
Day 40: -8.470736
Day 41: 203.523499

I wanted to group day 1 to 31 and sum up their total to print out in the last for loop. However, I am getting this error message:

TypeError: 'dict_values' object does not support indexing

at line month_groups[month] = month_groups.values()[month] + value

Any ideas how to fix this? Thanks!

Upvotes: 0

Views: 76

Answers (1)

Skyler
Skyler

Reputation: 656

Make the following change,

month_groups = defaultdict(int)

Then you can just do

month_groups[month] += value

Refer here regarding your error

Upvotes: 1

Related Questions