Python: sort list based on value present in dictionary -
consider list x = [obj1,obj2,obj3,obj4,obj5]
grouped in manner
obj1.freq = obj2.freq = frequency1 , obj3.freq = obj4.freq = obj5.freq = frequency2
and have dict
y = {obj1 : 40, obj2 :50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20}
i have sort list x considering obj of same frequency , sort based on values of obj present in dict , final result should
x = [obj2,obj1, obj5,obj3,obj4]
1st consider obj1
, obj2
because belong same frequency , sort looking values in dict y
. obj2
value 50
, obj1
value 40
.
so list x
sorted such 1st element obj2
followed obj1
and have same next set of objects belonging same frequency , sort based on value present in dict y how do ?
this code uses tuple (frequency, value-in-y)
sort key; list sorted in reverse order, highest frequency comes first (was not specified in question, if wrong, can use -i.freq
there); objects having frequencies sorted second item in tuple (the value dictionary y
, if any, or 0:
class obj: def __init__(self, name, freq): self.freq = freq self.name = name def __repr__(self): return self.name obj1 = obj('obj1',42) obj2 = obj('obj2',42) obj3 = obj('obj3',6) obj4 = obj('obj4',6) obj5 = obj('obj5',6) obj6 = obj('obj6',332) obj7 = obj('obj7',123) x = [obj2, obj1, obj5, obj3, obj4] y = {obj1:40, obj2:50, obj3:60, obj4:10, obj5:70, obj6:30, obj7:20} print(sorted(x, key=lambda i: (i.freq, y.get(i, 0)), reverse=true))
prints
[obj2, obj1, obj5, obj3, obj4]
Comments
Post a Comment