Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dictionary by multiple values

Tags:

I have the dictionary {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}

I need to sort this dictionary first numerically, then within that, alphabetically. If 2 items have the same number key, they need to be sorted alphabetically.

The output of this should be Bob, Alex, Bill, Charles

I tried using lambda, list comprehension, etc but I can't seem to get them to sort correctly.

like image 334
Infiniti Avatar asked Dec 09 '15 04:12

Infiniti


People also ask

How do you sort a dictionary by multiple values?

Sort Dictionary Using the operator Module and itemgetter() This function returns the key-value pairs of a dictionary as a list of tuples. We can sort the list of tuples by using the itemgetter() function to pull the second value of the tuple i.e. the value of the keys in the dictionary.

How do you sort multiple values in a dictionary python?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

Can we sort dictionary values?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

Can you use sort on a dictionary python?

Introduction. We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.


1 Answers

Using sorted with key function (order by value (d[k]) first, then key k):

>>> d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}     >>> sorted(d, key=lambda k: (d[k], k)) ['Bob', 'Alex', 'Bill', 'Charles'] 
like image 178
falsetru Avatar answered Oct 22 '22 05:10

falsetru