mrsolupo mrsolupo - 1 year ago 109
Python Question

Python How to top list of dicts up

[{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}]

I have this list. This is aggregation of months and some values. How to top it up by 0 to get something like this?

[0, 0, 0, 0, 0, 0, 0, 11, 20, 0, 0, 0, 0]

This first list has dicts with only this months which has something in sumd. If month does't have any information in sumd it will not be in list.

But in second list I need only value from sumd order by months number(but with all months - if any months was not in first list, set 0.)

Answer Source

If i understood what you want to do, the result would be a list of 12 elements not 13.

So if you cant to put the value of the month number (value of the month key) in the array representing a year (12 elements) you can do this :

month_dictionaries = [{'month': 7.0, 'sumd': 11}, {'month': 8.0, 'sumd': 20}]

result = [0] * 12

for d in month_dictionnaries:
    if 'sumd' in d.keys():
        result[int(d['month']) - 1] = d['sumd']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download