How would you go about displaying the order of the variables in python after using sort()
. For an example:
A=3
B=1
C=2
D=[A,B,C]
D.sort()
would be [1,2,3]
, but I want to see [B,C,A]
somehow
How would you go about displaying the order of the variables in python after using sort()
. For an example:
A=3
B=1
C=2
D=[A,B,C]
D.sort()
would be [1,2,3]
, but I want to see [B,C,A]
somehow
Doing this with independent variables just floating around would be extremely difficult. Why not use a dictionary instead?
myDict = {"A":3, "B":1, "C":2}
D = ["A", "B", "C"]
D.sort(key=lambda l:myDict[l])
Here we have each letter and its corresponding number in a dictionary. We have a list of letters out of order, which we call sort()
on. Instead of using the default comparisons however, we provide our own sorting function in the form of an inline lambda function, which gets the number from the dictionary that matches each letter.
In case you aren't familiar with the lambda syntax, it is the same as doing this but more compact:
def customSort(l):
return myDict[l]
D.sort(key=customSort)
Using collections.OrderedDict
, you can feed a list of key-value pairs sorted by value.
from collections import OrderedDict
from operator import itemgetter
d = {'A': 3, 'B': 1, 'C': 2}
res = OrderedDict(sorted(d.items(), key=itemgetter(1)))
# get keys ordered by value
print(res.keys())
odict_keys(['B', 'C', 'A'])
# get ordered values
print(res.values())
odict_values([1, 2, 3])