Value sort of dictionary with complicated structure (sort by key structure by deep value)

It's also called Complex Value Sort (what sort is this?)

--Case where the value of the specified dictionary has a structure --Sort the structure below the key by some value in the value of the complicated dictionary. --- Sort by maintaining the structure below the key. --Be careful whether the specified value is a character string or a numerical value. (Play "" and None in advance or set it to 0)

For example, there is such a dictionary structure

Adic = {
↓ Here or ↓ I want to sort around here
            'C134':{"price":30,"sales":"1000","profit":200 ,"alist":[110,20,30 ,50]}, 
            'C623':{"price":80,"sales":"100" ,"profit":6   ,"alist":[100,10,30 ,50]},
            'C430':{"price":70,"sales":"5000","profit":1000,"alist":[160,11,120,6]},
            'C115':{"price":10,"sales":"2400","profit":40  ,"alist":[80 , 1,10 ,6]}
        }

The point is the expression of the return value of the lambda expression

Use sorted () to specify the values you want to sort in the Value structure (in this case x [1] is the inner dictionary type).  key = lambda x: x[1]['profit']

Need to follow if the value you want to specify is deeper (x [1] ['alist'] corresponds to the list, specify the second one)  key = lambda x: x[1]['alist'][1]

Basically this

dic = {'A':10000, 'B':2010, 'C':5, 'D':500} res = sorted (dic.items (), key = lambda x: x [1]) #value specification res = sorted (pathD.items (), key = lambda x: int (x [0])) # By the way, sort is specified by key when key is str

Lambda can be read if you think of it as an abbreviation for a function.

def lambda(x): return 2x --> lambda x:2x

In the dict type, the (key, value) tuple jumps into x, so 0 or 1 is specified.

import collections
from prettyprint import pp, pp_str #I like pp, so please have an official one recently
from collections import OrderedDict

Adic = {
            #Sort these 4 columns by value value somewhere in value
            'C134':{"price":30,"sales":"1000","profit":200 ,"alist":[110,20,30,50]}, 
            'C623':{"price":80,"sales":"100" ,"profit":6   ,"alist":[100,10,30,50]},
            'C430':{"price":70,"sales":"5000","profit":1000,"alist":[160,11,120,6]},
            'C115':{"price":10,"sales":"2400","profit":40  ,"alist":[80,1,10,6]}
        }

#It feels like the tuples from the dictionary are in x. Specify Value by tracing through the tuple
#Note that it will be returned as a List
#All specified in descending order:reverse=True
pp('Sort by profit')
res1 = sorted(Adic.items(), key=lambda x: x[1]['profit'],reverse=True)
pp(res1)

pp('Sort by sales (string converted to int)')
res2 = sorted(Adic.items(), key=lambda x: int(x[1]['sales']),reverse=True)
pp(res2)

pp('Sort by the second alist')
res3 = sorted(Adic.items(), key=lambda x: x[1]['alist'][1],reverse=True)
pp(res3)

pp('key sort (Pull out numbers from the back with 3 numbers. If 3 digits or fixed)')
res4 = sorted(Adic.items(), key=lambda x: int (x[0][-3]) ,reverse=True)#Somehow even without an int
pp(res4)

pp('key sort (first character"C"Cut)')
res5 = sorted(Adic.items(), key=lambda x: int(x[0].lstrip('C')) ,reverse=True)
pp(res5)

pp('Sort by profit 2')
res6 = OrderedDict(sorted(Adic.items(), key=lambda x: x[1]['profit'],reverse=True))
print(res6)#If it is pp, the order will be broken.
pp(type(res6))

result

I will paste only the profit case for the time being. The profit values, 1000, 200, 40, 6 can be sorted by structure in descending order! In terms of key, the structural order is c430, c134, c115, c623.

"Sort by profit"
[
    [
        "C430", 
        {
            "alist": [
                160, 
                11, 
                120, 
                6
            ], 
            "price": 70, 
            "profit": 1000, 
            "sales": "5000"
        }
    ], 
    [
        "C134", 
        {
            "alist": [
                110, 
                20, 
                30, 
                50
            ], 
            "price": 30, 
            "profit": 200, 
            "sales": "1000"
        }
    ], 
    [
        "C115", 
        {
            "alist": [
                80, 
                1, 
                10, 
                6
            ], 
            "price": 10, 
            "profit": 40, 
            "sales": "2400"
        }
    ], 
    [
        "C623", 
        {
            "alist": [
                100, 
                10, 
                30, 
                50
            ], 
            "price": 80, 
            "profit": 6, 
            "sales": "100"
        }
    ]
]



#Remarks
#Relationship between lambda expressions and functions
def func(x):
    return x ** 2

func = lambda x: x ** 2
func(2) #4

#string processing
string.strip()#Delete all blank line breaks
string.strip("\n\r")#Delete hits at both ends
string.rstrip("\n\r")#Delete what hits with a ketsu

Recommended Posts

Value sort of dictionary with complicated structure (sort by key structure by deep value)
Sort dict in dict (dictionary in dictionary) with a specific key
Get the value of a specific key in a list from the dictionary type in the list with Python
Sort by dict type value value
Sort of tuple array can be accelerated by specifying key (Python)
Expansion by argument of python dictionary
Replace dictionary value with Python> update ()
Try deep learning of genomics with Kipoi
Dictionary key error → Resolve with key in dicionary
Sentiment analysis of tweets with deep learning
Search pythondict dictionary key by regular expression
[https proxy with squid] Resolution of error caused by dh key too small