Tanzeel Ahmed
Tanzeel Ahmed

Reputation: 11

How do I sort the dictionary which consists of tuples

I expect to sort this dictionary based on second values of tuples

print(normalizedTermFrequency)

c=sorted(normalizedTermFrequency.items(),key=lambda t:t[1][1],reverse=True)

print(c)

The Output:

{0: [('the', 0.2857142857142857), ('universe', 0.14285714285714285), ('has', 0.14285714285714285), ('very', 0.14285714285714285), ('many', 0.14285714285714285), ('stars', 0.14285714285714285)], 1: [('the', 0.2), ('galaxy', 0.2), ('contains', 0.2), ('many', 0.2), ('stars', 0.2)], 2: [('the', 0.1), ('cold', 0.2), ('breeze', 0.1), ('of', 0.1), ('winter', 0.1), ('made', 0.1), ('it', 0.1), ('very', 0.1), ('outside', 0.1)]}

[(0, [('the', 0.2857142857142857), ('universe', 0.14285714285714285), ('has', 0.14285714285714285), ('very', 0.14285714285714285), ('many', 0.14285714285714285), ('stars', 0.14285714285714285)]), (1, [('the', 0.2), ('galaxy', 0.2), ('contains', 0.2), ('many', 0.2), ('stars', 0.2)]), (2, [('the', 0.1), ('cold', 0.2), ('breeze', 0.1), ('of', 0.1), ('winter', 0.1), ('made', 0.1), ('it', 0.1), ('very', 0.1), ('outside', 0.1)])]

But as we can see in the second output for the second key 0.1 appears before 0.2 How do I solve this?

Upvotes: 0

Views: 39

Answers (1)

gstukelj
gstukelj

Reputation: 2551

If you just want a list of sorted tuples you can go with something ugly like:

sorted([y for x in dic.values() for y in x], key=lambda x: x[1], reverse=True)

If you want to sort the values but preserve the mappings, this should do:

for key, value in dic.items():
    dic[key] = sorted(dic[key], key=lambda x: x[1], reverse=True)

Where dic is your dictionary.

Upvotes: 1

Related Questions