Skip to content Skip to sidebar Skip to footer

How To Order By Date Defaultdict(list) Value?

defaultdict(, {'003': [('Biology', 'A', '04/18/2013'), ('Irdu', 'A' , '04/17/2013')], '002': [('Biology', 'A', '03/01/2013'), ('Math', 'C', '01/10/2 013'), ('Mat

Solution 1:

I think you want something like :

key = itemgetter(2)
sortedData = {}
for k, v in accounts.items():
    v.sort(key=key)
    sortedData[k] = v

or

sortedData = {(k, list(sorted(v, key=key)) for k, v in accounts.items()}

Solution 2:

iteritems returns an iterator of key/value pairs. If you want to use it, you'll have to skip the keys and sort the values. If you want to actually modify the defaultdict itself, an in-place sort would be best:

getter = operator.itemgetter(2)
for v in accounts.itervalues():
    v.sort(key=getter)

If you want a new defaultdict, you can use a generator expression:

getter = operator.itemgetter(2)
sortedData = defaultdict(list,
    {k: sorted(v, key=getter) for k, v in accounts.iteritems()})

Solution 3:

This should do the trick:

from collections import defaultdict
from datetime import datetime

d = defaultdict(list, {'003': [('Biology', 'A', '04/18/2013'), ('Irdu', 'A', '04/17/2013')], '002': [('Biology', 'A', '03/01/2013'), ('Math', 'C', '01/10/2013'), ('Math', 'C', '03/10/2013')], '001': [('Biology', 'B', '05/01/2013'), ('Literature', 'B', '03/02/2013'), ('Math', 'A', '02/20/2013')]})

def key(entry):
    _, _, date_string = entry
    date_entry = datetime.strptime(date_string, '%m/%d/%Y').date()
    return (date_entry.year, date_entry.month, date_entry.day)

{k: sorted(v, key=key) for k,v in d.iteritems()}
>>> {
'001': [('Math', 'A', '02/20/2013'),
    ('Literature', 'B', '03/02/2013'),
    ('Biology', 'B', '05/01/2013')],
'002': [('Math', 'C', '01/10/2013'),
    ('Biology', 'A', '03/01/2013'),
    ('Math', 'C', '03/10/2013')],
'003': [('Irdu', 'A', '04/17/2013'), ('Biology', 'A', '04/18/2013')]
}

Post a Comment for "How To Order By Date Defaultdict(list) Value?"