Home > Back-end >  How to make this code loop through the dictionary to create another dictionary
How to make this code loop through the dictionary to create another dictionary

Time:12-30

I wish to create a dictionary which is a summary of a dictionary describing temperatures in Prague. The code below correctly extracts the first key: value pair. The issue is how to get all key: value pairs like this:

sum_dict = {1775: 4, 1778: 16, 1781: 7, ...}

test_dict= {1775: 3, 1776: 1, 1778: 3, 1779: 12, 1780:1, 
1781: 5, 1782: 2, 1784: 8, 1786: 3, 1787: 4}

sum = 0
for key, value in test_dict.items():
    years = list(range(1775, 1778))
    for year in years:
        if key == year:
            sum = value   sum

# Create dictionary pair with 1st date in years and sum 
the values

sum_dict = {}
sum_dict[years[0]] = sum
print(sum_dict)

years = [a 3 for a in years]             
print(years)

CodePudding user response:

Try:

test_dict = {
    1775: 3,
    1776: 1,
    1778: 3,
    1779: 12,
    1780: 1,
    1781: 5,
    1782: 2,
    1784: 8,
    1786: 3,
    1787: 4,
}

_min, _max = min(test_dict), max(test_dict)

sum_dict = {
    year: sum(test_dict.get(y, 0) for y in range(year, year   3))
    for year in range(_min, _max, 3)
}
print(sum_dict)

Prints:

{1775: 4, 1778: 16, 1781: 7, 1784: 11}
  • Related