How to order by date defaultdict (list) value?

defaultdict(<type 'list'>, {'003': [('Biology', 'A', '04/18/2013'), ('Irdu', 'A' , '04/17/2013')], '002': [('Biology', 'A', '03/01/2013'), ('Math', 'C', '01/10/2 013'), ('Math', 'C', '03/10/2013')], '001': [('Biology', 'B', '05/01/2013'), ('L iterature', 'B', '03/02/2013'), ('Math', 'A', '02/20/2013')]}) 

I want to sort each key by date and get the following output

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

I tried the following but did not think about it?

 accounts = defaultdict(list) sortedData = sorted(accounts.iteritems(), key=operator.itemgetter(2)) 
0
source share
3 answers

I think you need 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()} 
+2
source

iteritems returns an iterator of key / value pairs. If you want to use it, you will have to skip the keys and sort the values. If you want to actually change the defaultdict itself, the best way to post in place is:

 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()}) 
+1
source

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')] } 
+1
source

Source: https://habr.com/ru/post/1482245/


All Articles