[python] Dictionary keys, sorting by value


   Dictionaries in Python are unordered by default, and many application scenarios require sorting the keys and values ​​of the dictionary. Therefore, dictionary sorting in Python has become a frequent topic in interviews.

  Before entering the text, let us first create a dictionary with name as the key and age as the value :

d = {
    
    'Caitlyn': 21, 'Darius': 45, 'Bard': 33, 'Ezreal': 24, 'Akali': 31, 'Fiora': 43}

  How to sort the dictionary according to keys and values?

>>> d.keys()
dict_keys(['Caitlyn', 'Darius', 'Bard', 'Ezreal', 'Akali', 'Fiora'])
>>> d.values()
dict_values([21, 45, 33, 24, 31, 43])

1. Sort by key

1.1 Analysis of ideas

Before sorting the keys, obtain the list of keys:

>>> list(d.keys())
['Caitlyn', 'Darius', 'Bard', 'Ezreal', 'Akali', 'Fiora']

Sort the list by sorted:

>>> sorted(list(d.keys())) 
['Akali', 'Bard', 'Caitlyn', 'Darius', 'Ezreal', 'Fiora']

sorted in python supports sorting keys directly:

>>> sorted(d.keys())        
['Akali', 'Bard', 'Caitlyn', 'Darius', 'Ezreal', 'Fiora']

If it is reverse order, just set "reverse=True"

>>> sorted(d.keys(), reverse=True) 
['Fiora', 'Ezreal', 'Darius', 'Caitlyn', 'Bard', 'Akali']

After that, the generation of ordered dictionary can be achieved by combining the production formula :

>>> {
    
    k:d[k] for k in sorted(d.keys())} 
{
    
    'Akali': 31, 'Bard': 33, 'Caitlyn': 21, 'Darius': 45, 'Ezreal': 24, 'Fiora': 43}
>>> dict(sorted(d.items()))                        
{
    
    'Akali': 31, 'Bard': 33, 'Caitlyn': 21, 'Darius': 45, 'Ezreal': 24, 'Fiora': 43}

1.2 Summary of methods

dict(sorted(d.items()))
dict(sorted(list(d.items())))
dict(sorted(list(dic.items()),key=lambda x:x[0]))
{
    
    k:d[k] for k in sorted(d.keys())} 
{
    
    k:d[k] for k in sorted(list(d.keys()))} 
dict(sorted([(k,v) for k,v in d.items()])
dict(sorted([(k,v) for k,v in d.items()],key=lambda x:x[0]))

2. Sort by value

2.1 Analysis of ideas

2.1.1 Generate a list of key-value pair tuples

Sorting by value must bind the key to sort, otherwise the key cannot be obtained based on the value. Here we use the zip build generator for binding:

>>> zip(d.keys(),d.values())     
<zip object at 0x000001F676EF8840>

Then convert it into a list for subsequent sorting:

>>> list(zip(d.keys(),d.values()))
[('Caitlyn', 21), ('Darius', 45), ('Bard', 33), ('Ezreal', 24), ('Akali', 31), ('Fiora', 43)]

The above two steps can also use tuple lists to achieve key-value binding:

>>> [(k,d[k]) for k in d.keys()] 
[('Caitlyn', 21), ('Darius', 45), ('Bard', 33), ('Ezreal', 24), ('Akali', 31), ('Fiora', 43)]

2.1.2 Sorting the list of key-value tuples

Then use the sorted method to specify that the tuples are sorted by value (x[1]):

>>> sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])
[('Caitlyn', 21), ('Ezreal', 24), ('Akali', 31), ('Bard', 33), ('Fiora', 43), ('Darius', 45)]

You can also sort list(zip()):

>>> sorted(list(zip(d.keys(), d.values())), key=lambda x:x[1]) 
[('Caitlyn', 21), ('Ezreal', 24), ('Akali', 31), ('Bard', 33), ('Fiora', 43), ('Darius', 45)]

Python also supports direct sorting of zip():

>>> sorted(zip(d.keys(), d.values()), key=lambda x:x[1])       
[('Caitlyn', 21), ('Ezreal', 24), ('Akali', 31), ('Bard', 33), ('Fiora', 43), ('Darius', 45)]

To set descending order by age, use reverse=True:

>>> sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1], reverse=True) 
[('Darius', 45), ('Fiora', 43), ('Bard', 33), ('Akali', 31), ('Ezreal', 24), ('Caitlyn', 21)]

2.1.3 Generate dictionary based on list

Then use the dictionary generation method to generate the dictionary:

>>> {
    
    tup[0]:tup[1] for tup in sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])} 
{
    
    'Caitlyn': 21, 'Ezreal': 24, 'Akali': 31, 'Bard': 33, 'Fiora': 43, 'Darius': 45}

2.2 Summary of methods

dict(sorted(d.items(),key=lambda x:x[1]))
dict(sorted(list(d.items()),key=lambda x:x[1]))
dict(sorted([(k,v) for k,v in d.items()],key=lambda x:x[1]))

{
    
    k:v for (k,v) in sorted(zip(d.keys(),d.values()), key=lambda x:x[1])}
{
    
    k:v for (k,v) in sorted(list(zip(d.keys(),d.values())), key=lambda x:x[1])}

{
    
    k:v for (k,v) in sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])}
{
    
    k:d[k] for (k,v) in sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])}
{
    
    tup[0]:tup[1] for tup in sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])}
{
    
    tup[0]:d[tup[0]] for tup in sorted([(k,d[k]) for k in d.keys()], key=lambda x:x[1])}

Recommended reading:
[python] Summary of dictionary creation methods
[python] Use of generative expressions
For more usage methods and applications of python, please pay attention to subsequent updates~

Guess you like

Origin blog.csdn.net/weixin_44844635/article/details/131381675