![]() So unlike previous versions, you can sort a dict after Python 3.6/3.7. Suppose you want to sort the following list of dictionaries with primary key 'name' ascending, and secondary key 'surname' descending. Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). ![]() the keys support comparison but not negation. The typical method for sorting dictionaries is to get a dictionary view, sort it, and then cast the resulting list back into a dictionary. Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary: Use the sorted () function with key argument to create a new dic. The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries. Use the itemgetter function as key function to sort the list of dictionaries. To supplement rather than repeat what is stated in the other answers, this question raises an interesting point (although not directly needed in the case in the question) about what happens if you want to sort on two keys, with the primary ascending and the secondary descending, but where neither key is numeric so you cannot employ the trick of negating one of the keys - i.e. But must be used like follows: yourlistsorted sorted (yourlist, keyitemgetter ('name','age')) Here is the alternative general solution - it sorts elements of dict by keys and values.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |