Edited: I need to change the rule. I have a list of dictionaries like this:
A=[{0:[(0,0,2,1),(0,1,2,1)]},{1:(0,1,1,3)},{2:[(1,2,2,2)]},{3:(0,0,1,4),(0,1,1,4),(1,0,1,4)}]
First, I need to count the number of elements in each dictionary. Second, calculate multiply the last two elements for one of the elements in each list(because at each list the last two elements are the same), like this:
M=[(0,2,2) ,(1,3,1) , (2,4,1) , (3,4,3)]
the first element is the key, the second is the multiply of the last two elements, and the third is the number of elements in that list. (I don't need to print this part) then for each list calculate multiply/options, like this:
B=[(0,2/2), (1,3/1), (2,4/1), (3,4/3)]
I need the output to be a list of keys with the large to small the second element:
output: [2, 1, 3, 0]
Does anyone have any idea that could help?
New Solution as per edit
t=[{0:[(0,0,2,1),(0,1,2,1)]},{1:[(0,1,1,3)]},{2:[(1,2,2,2)]},{3:[(0,0,1,4),(0,1,1,4),(1,0,1,4)]}]
step_one=[]
for i in t:
key_list=list(i.keys())
value_list=list(i.values())
first=key_list[0]
second=value_list[0][0][-1]*value_list[0][0][-2]
third=len(value_list[0])
step_one.append((first,second,third))
print(step_one) # [(0, 2, 2), (1, 3, 1), (2, 4, 1), (3, 4, 3)]
step_two=[(i,j/k) for i,j,k in step_one]
step_three=[i for i,j in sorted(step_two,key=lambda x:-x[1])]
print(step_three) # [2, 1, 0, 3]
Will this work? Use the key
parameter to perform your sort
t=[{0:[(0,0,1,3),(0,1,1,3)]},{1:[(0,1,1,3)]},{3:[(0,0,1,3),(0,1,1,3),(1,0,4,1)]}]
sorted_t=sorted(t,key=lambda x:len(list(x.values())[0]))
result=[list(i.keys())[0] for i in sorted_t]
print(result) # [1, 0, 3]
Breakdown
sorted_t=sorted(t,key=lambda x:len(list(x.values())[0]))
this will sort the list based on "length of first value in the dict" for each element
Result : [{1: [(0, 1, 1, 3)]}, {0: [(0, 0, 1, 3), (0, 1, 1, 3)]}, {3: [(0, 0, 1, 3), (0, 1, 1, 3), (1, 0, 4, 1)]}]
Then iterate through sorted_t
and get the "key for each dict in the sorted list", [0]
is for indexing the element from the "key list". Otherwise you will end with a list like [[1], [0], [3]]