I have a list like this
[u'201003', u'200403', u'200803', u'200503', u'201303',
u'200903', u'200603', u'201203', u'200303', u'200703', u'201103']
lets call this list as 'years_list'
When I did groupby year,
group_by_yrs_list = groupby(years_list, key = lambda year_month: year_month[:-2])
for k,v in group_by_yrs_list:
print k, list(v)
I got the desired output:
2010 [u'201003']
2004 [u'200403']
2008 [u'200803']
2005 [u'200503']
2013 [u'201303']
2009 [u'200903']
2006 [u'200603']
2012 [u'201203']
2003 [u'200303']
2007 [u'200703']
2011 [u'201103']
Then, I slightly changed my implementation like this,
group_by_yrs_list = dict(groupby(years_list, key = lambda year_month: year_month[:-2]))
for k,v in group_by_yrs_list.items():
print k, list(v)
I have just added a dict, but the output is different,
2003 []
2006 []
2007 []
2004 []
2005 []
2008 []
2009 []
2011 [u'201103']
2010 []
2013 []
2012 []
I couldn't find out why. Please help me to find what the dict is doing actually.
(Python 2.7)
groupby
yields pairs of (key, iterator-of-group). If you are iterating the second pair, the iterator-of-group of the first pair is already consumed, so you get empty list.
Try following code:
group_by_yrs_list = {year:list(grp) for year, grp in groupby(years_list, key=lambda year_month: year_month[:-2])}
for k, v in group_by_yrs_list.items():
print k, v
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With