Python sort dictionary by value

Source:https://stackabuse.com/how-to-sort-dictionary-by-value-in-python/

Method 1

dict1 = {1: 1, 2: 9, 3: 4}
sorted_values = sorted(dict1.values()) # Sort the values
sorted_dict = {}

for i in sorted_values:
    for k in dict1.keys():
        if dict1[k] == i:
            sorted_dict[k] = dict1[k]
            break

print(sorted_dict)

Method 2

dict1 = {1: 1, 2: 9, 3: 4}
sorted_dict = {}
sorted_keys = sorted(dict1, key=dict1.get)  # [1, 3, 2]

for w in sorted_keys:
    sorted_dict[w] = dict1[w]

print(sorted_dict) # {1: 1, 3: 4, 2: 9}

Python: sort an array of tuple by the second element value

Note that it works equally well with an array of arrays.

# function to return the second element of the
# two elements passed as the parameter
def sortSecond(val):
	return val[1]

# list1 to demonstrate the use of sorting
# using second key
list1 = [(1,2),(3,3),(1,1)]

# sorts the array in ascending according to
# second element
list1.sort(key=sortSecond)
print(list1)

# sorts the array in descending according to
# second element
list1.sort(key=sortSecond,reverse=True)
print(list1)

Source: https://www.geeksforgeeks.org/sort-in-python/

Python environment

To better control the development environment of your python project and ensure that your older project don’t break when updating packages, it is recommended to create a dedicated environment for your project.

For that purpose you can use python virtual environment.

Create environment:

python3 -m venv env

Activate environment:

source env/bin/activate