How can I get a ranked list from a dictionary?

I work in Python. The dictionary that I have is as follows:

score = {'a':{4:'c', 3:'d'}, 'b':{6:'c', 3:'d'}} 

And I need to order it like this:

 rank = [{a:3, b:6}, {a:4, b:3}] 

If the sub-dictionary with the largest combination of exclusive key values ​​is in the first element, the second largest combination of exclusive key values ​​is in the second element, and so on. The biggest combinational logic: 1. Take the largest combination (total amount) of keys from each dictionary (in this case it will be β†’ 4: 'c' and b-> 6: 'd'. Remove these values ​​from the dictionary and take the next a large key combination (in this case it will be a-> 4: 'c' and b-> 3: 'd'). This should continue until the original dictionary becomes empty.

This is exclusive, because once a value has been used from the original dict, it should be removed or excluded from use again in any future combinations.

I tried all the different approaches that I know, but algorithmically I am missing something.

+5
source share
1 answer

Think I did what you are looking for? This is a strange algorithm and it is a little dirty due to the try / except block, but it works.

Edit: added comments and deleted unnecessary code.

 def rank(toSort): #importing from the string library from string import lowercase as alph #temporary list _ranks=[] #populate with empty dictonaries for i in range(len(toSort)): _ranks.append({}) #the actual sorting algorithm for i in range(len(toSort)-1): #iterate all k/v pairs in the supplied dictionary for k,v in toSort.iteritems(): #iterate all k/v pairs in v element for a,b in v.iteritems(): #if the alpha index of an element is equal to #the max alpha index of elements in its containing dictionary... if alph.index(b)==max(map(alph.index,v.values())): _ranks[i][k]=a #if it isn't.. else: try: _ranks[i+1][k]=a except IndexError: _ranks[-1][k]=a return _ranks 
+1
source

Source: https://habr.com/ru/post/1242470/


All Articles