0

I want to sort a dictionary by descending order by a value of a key within a key. In my sample, I want to sort by little 'c'

Here is what I looks like now:

sample = {'A': {'a':22, 'b':24, 'c':80},
 'B': {'a':12, 'b':13, 'c':55},
 'C': {'a':44, 'b':33, 'c':99}
}

and here is my desired output:

sample = {'C': {'a':44, 'b':33, 'c':99},
 'A': {'a':22, 'b':24, 'c':80},
 'B': {'a':12, 'b':13, 'c':55}
}

I tried this bit of code by clearly its not right:

newdict = {}
for key, value in sorted(sample.items(), key=lambda item: item['c'], reverse=True):
     newdict[key] = value
sample = newdict

Thank you all for the help in solving this little puzzle!

1 Answer 1

1

You're close, the key function should be:

key=lambda item: item[1]['c']

Rewritten to be more Pythonic:

sample = dict(sorted(sample.items(), key=lambda item: item[1]['c'], reverse=True))

(The dict constructor can take an iterable of item tuples)

Sign up to request clarification or add additional context in comments.

1 Comment

you sir, are brilliant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.