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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With