Answer the question
In order to leave comments, you need to log in
How to sort dictionary via sorted() using lambda in key parameter?
We have a dictionary of dictionaries, which we get like this
for elem in cur.fetchall():
if elem[0] in publist:
publist[elem[0]]["cat_id"].add(elem[5])
else:
publist[elem[0]]={"title": elem[1],
"text": elem[2],
"date": elem[3],
"author": elem[4],
"cat_id": {elem[5]
}}
pub_sorted=sorted(publist,
key=lambda elem:datetime.strptime(elem["date"], "%d.%m.%Y %H:%M:%S"),
reverse=True)
TypeError: 'int' object is not subscriptable
worklist=[{"work_id": elem[0],
"title": elem[1],
"date": elem[2],
"customer": elem[3],
"author": elem[4],
"workfrom": elem[5],
"workto": elem[6]
} for elem in cur.fetchall()]
work_sorted=sorted(worklist(),
key=lambda work:datetime.strptime(work["workfrom"], "%d.%m.%Y"),
reverse=True)
Answer the question
In order to leave comments, you need to log in
sorted takes an iterable object.
sorted(publist, ...), where publist is a dictionary, iterates over the keys of the dictionary, this is how dictionary iteration works in python.
sorted(publist.items(), ...) - iterates over tuples of the form (key, value) from the dictionary.
It is from this that such an exit from sorted. She gives sorted, what she received.
By the way, only recently in python (3.7 officially and 3.6 in fact, sort of) the default dictionary remembers the order of the keys added to it.
Perhaps it is worth considering what and at what point in the code is more important: quick access to data by the dictionary key, or working with sorted data. You can sort at the moment when you really need it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question