How do i sort the following list B that is a subset of dictionary A, based on A's values?
A = {1: 10, 2:20, 3: 15, 4: 1}
B = [1, 3, 4]
My solution should be
B = [4, 1, 3]
since
A[4] < A[1] < A[3]
Use A.get
as key
A = {1: 10, 2:20, 3: 15, 4: 1}
B = [1, 3, 4]
>>> sorted(B, key=A.get)
[4, 1, 3]
Notice that you can set a default value as argument for the .get
method, such that, if a given key doesn't exist in your dict, you can set a position yourself (eg last position or first). For example:
B = [1, 3, 4, 11]
>>> sorted(B, key=lambda k: A.get(k, -1))
[11, 4, 1, 3]
>>> sorted(B, key=lambda k: A.get(k, float('inf')))
[4, 1, 3, 11]
Or, as highlighted by @jpp,
>>> sorted(B, key=A.__getitem__)
if you prefer a KeyError
to be raised if referenced key doesn't exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.