Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a ranked list from a dictionary?

I am working in Python. The dictionary I have looks like this:

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}]

Where the sub-dictionary with the greatest combination of exclusive key values is in the first element, the second greatest combination of exclusive key values is in the second element and so forth. The greatest combination logic would be: 1. Grab the biggest combination (total sum) of keys from each dictionary (in this case it would be a->4:'c' and b->6:'d'. Remove those values from the dictionary and grab the next biggest combination of keys (in this case, it would be a->4:'c' and b->3:'d'). This should continue until the original dictionary is empty.

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

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

like image 304
DanGoodrick Avatar asked Nov 08 '22 20:11

DanGoodrick


1 Answers

I think I made what you're looking for? It's a weird algorithm, and it's kinda dirty due to the try/except block, but it works.

Edit: added comments and removed unneeded 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
like image 137
Valkyrie Avatar answered Nov 14 '22 22:11

Valkyrie