Paradigm Paradigm - 2 years ago 68
Python Question

Sorting a list based on the 2nd key

I need help in sorting a list with 2 keys inside. For example, if I input "google" the output should be like this:

Letter: 'g', Frequency: 2
Letter: 'o', Frequency: 2
Letter: 'e', Frequency: 1
Letter: 'l', Frequency: 1

But instead, what I get is this:

Letter: 'e', Frequency: 1
Letter: 'g', Frequency: 2
Letter: 'l', Frequency: 1
Letter: 'o', Frequency: 2

Basically it just sorts the letters and not the frequency. What I wanted was for it to be sorted by Frequency first then by Letter. Here is my code snippet for the sorting part and a dictionary sample declaration:

adict = {'Letter':'a', 'Frequency':0}
bdict = {'Letter':'b', 'Frequency':0}
cdict = {'Letter':'c', 'Frequency':0}

def getKey(item):
return item['Frequency']

finalArr = sorted(newArr, key = getKey)

I've tried the lambda sorting and the itemgetter but it still sorts the letter.

Here's the Frequency updating part (not the whole part just a sample):

for ex in range(0, len(temp)):
if temp[count] == 'a': adict['Frequency']+=1
elif temp[count] == 'b': bdict['Frequency']+=1
elif temp[count] == 'c': cdict['Frequency']+=1

And here's if the Frequency is not 0 it will be assigned to a list:

if adict['Frequency'] != 0 : newArr.append(adict)
if bdict['Frequency'] != 0 : newArr.append(bdict)
if cdict['Frequency'] != 0 : newArr.append(cdict)

Answer Source

You can return a tuple from your key function:

def getKey(item):
    return (item['Frequency'], item['Letter'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download