Reputation: 317
I have a list of dictionaries as shown below. Each dictionary holds the total for a particular month. If a month doesn't appear in the list, for example January, it's total should be zero.
q = [{'total_item': 3, 'month': u'02'}, {'total_item': 1, 'month': u'03'}, {'total_item': 1, 'month': u'05'}, {'total_item': 5, 'month': u'06'}, {'total_item': 6, 'month': u'07'}, {'total_item': 1, 'month': u'10'}, {'total_item': 1, 'month': u'12'}]
I want to convert the above data structure to a simple list, where the ordinal position represent the month and the value represents the total items.
[0, 3, 1, 0, ...] # 12 entries in total - one for each month
That is Jan is 0, Feb is 3, March is 1 etc.
I know I can use something like this to get the values present:
result = [r['total_item'] for r in q]
but how do I create zero value entries for the months that are not present?
Upvotes: 0
Views: 1342
Reputation: 9953
And one more way to do it ... map existing months to their total_item
values and then use dict.get()
with a default of 0
:
nitems = dict((int(x['month']), x['total_item']) for x in q)
result = [nitems.get(i, 0) for i in range(1, 13)]
Upvotes: 1
Reputation: 27236
A shorter approach (Python ≥ 2.7 because of the dict comprehension):
>>> d={int(i["month"]):i["total_item"] for i in q} #create a easier to use dict
>>> d
{2: 3, 3: 1, 5: 1, 6: 5, 7: 6, 10: 1, 12: 1}
>>> [d.get(i,0) for i in range(1,13)] #d.get(i,0) returns 0 if i not in dict
[0, 3, 1, 0, 1, 5, 6, 0, 0, 1, 0, 1]
Upvotes: 0
Reputation: 11
Perhaps you might want to use scikits.timeseries:
http://pytseries.sourceforge.net/
For example:
import scikits.timeseries as TS
aDate = TS.Date('M', '2010-01-01')
myTS = TS.time_series(myData, start_date = aDate, freq = 'M')
From there you can fill missing values with zeros and export (I believe using myTS.fill(0)).
Upvotes: 1
Reputation: 2047
try:
>>> months = [0] * 12
>>> for r in q: months[int(r['month'])-1] = r['total_item']
>>> months
[0, 3, 1, 1, 1, 5, 6, 6, 0, 1, 1, 1]
Upvotes: 1
Reputation: 527183
result = [0]*12
for r in q:
result[int(r['month'])-1] = r['total_item']
Upvotes: 2
Reputation: 48795
Use this:
class MyDict(dict):
def __missing__(self, key):
self[key] = 0
return self[key]
And then you can use this object instead of a normal dictionary. It acts just like it, but when you access an item that doesn't exist, it will create it with a value of 0.
Upvotes: 1
Reputation: 523574
Just loop over the list, and assign according to the value of month.
total_items = [0]*12
for d in q:
month = int(d['month'], 10)
total_items[month-1] = d['total_item']
Upvotes: 3