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.
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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With