D
D
Dmitry Temnikov2020-07-03 21:45:25
Python
Dmitry Temnikov, 2020-07-03 21:45:25

How to sort dictionary via sorted() using lambda in key parameter?

We have a dictionary of dictionaries, which we get like this

Getting a dictionary of dictionaries
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]
                                 }}
Trying to sort like this
Sorting
pub_sorted=sorted(publist,
                key=lambda elem:datetime.strptime(elem["date"], "%d.%m.%Y %H:%M:%S"),
                reverse=True)

We get an error . It seems that sorted gives the keys of the dictionary to the incoming key parameters, it is clear that they are not called by the key CHTYADNT tell me pliz? A similar muddle with a list of dictionaries rolls normallyTypeError: 'int' object is not subscriptable

Getting a list of dictionaries
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()]
Sorting
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

1 answer(s)
R
Ruslan, 2020-07-04
@exibit777

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 question

Ask a Question

731 491 924 answers to any question