Python dictionary is sorted by key and value

Sorting first thought of python's sorted() and sort()

The difference between sort and sorted:
1.sort is a method applied to the list, and sorted can sort all iterable objects.
2. The sort method of list returns an operation on an existing list, while the built-in function sorted method returns a new list, not an operation on the original basis. In layman's terms, sort has no return value, sorted has a return value.

sorted 语法: sorted(iterable, key=None, reverse=False)

Parameter Description:

iterable-iterable object.
key-It is mainly used to compare the element. There is only one parameter. The parameter of the specific function is taken from the iterable object and specifies an element in the iterable object for sorting .
reverse-sorting rule, reverse = True for descending order, reverse = False for ascending order (default).

Therefore, the dictionary is sorted by key and value, that is, the key or value is selected in the parameter key in sorted().

import random
testlist=[]
for i in range(20):
    testlist.append(random.randint(81,100))
print(testlist)
zi={
    
    }
for x in testlist:
    if x not in zi.keys():
        zi[x]=testlist.count(x)
print("zi:",zi)

# 按照键排序
ll1=sorted(zi.items(),key=lambda kv:(kv[0]))
print(ll1)
#按照值排序
ll2=sorted(zi.items(),key=lambda kv:(kv[1]))
print(ll2)

The output is:

[88, 97, 90, 88, 99, 95, 95, 95, 86, 93, 97, 90, 95, 98, 100, 86, 99, 90, 84, 84]
zi: {
    
    88: 2, 97: 2, 90: 3, 99: 2, 95: 4, 86: 2, 93: 1, 98: 1, 100: 1, 84: 2}
[(84, 2), (86, 2), (88, 2), (90, 3), (93, 1), (95, 4), (97, 2), (98, 1), (99, 2), (100, 1)]
[(93, 1), (98, 1), (100, 1), (88, 2), (97, 2), (99, 2), (86, 2), (84, 2), (90, 3), (95, 4)]

1. The Python dictionary items() function returns a traversable (key, value) tuple array as a list.
2. The lambda function can refer to: python's lambda-map-reduce

Dictionary sorted list :

lis = [{
    
     "name" : "Taobao", "age" : 100},  
{
    
     "name" : "Runoob", "age" : 7 }, 
{
    
     "name" : "Google", "age" : 100 }, 
{
    
     "name" : "Wiki" , "age" : 200 }]

lname=sorted(lis,key=lambda kv:kv['name'])
print(lname)
lage=sorted(lis,key=lambda kv:kv['age'])
print(lage)

The output is:

[{
    
    'name': 'Google', 'age': 100}, {
    
    'name': 'Runoob', 'age': 7}, {
    
    'name': 'Taobao', 'age': 100}, {
    
    'name': 'Wiki', 'age': 200}]
[{
    
    'name': 'Runoob', 'age': 7}, {
    
    'name': 'Taobao', 'age': 100}, {
    
    'name': 'Google', 'age': 100}, {
    
    'name': 'Wiki', 'age': 200}]

Guess you like

Origin blog.csdn.net/liulanba/article/details/114384960