dict dictionary elements by key or value sorting

 Use the built-sorted python method, you can easily sort the elements dict 

 

IF  the __name__ == ' __main__ ' : 
    my_dict = {} 
    my_dict [ ' the CD ' ] = 12 is 
    my_dict [ ' XA ' ] = 60 
    my_dict [ ' BJ ' ] = 15 
    my_dict [ ' GZ ' ] = 100
     # After sorting, the original dict and it did not change, resulting in a new dict 
    value_sorted_result the sorted = (my_dict. items (), Key = the lambda Item: Item [. 1], Reverse = True)   # by descending value 
    print(value_sorted_result) // [( 'GZ', 100), ( 'XA', 60), ( 'BJ', 15), ( 'the CD', 12 is)] 

    # Press sort key 
    key_sorted_result = sorted (my_dict.items (), key = the lambda Item: Item [0], Reverse = True)   # press key descending 
    Print (key_sorted_result)

Guess you like

Origin www.cnblogs.com/z-qinfeng/p/12109731.html