1

I want to sort by the 'idx' value in the following dictionary, to create a list of dictionaries

episodes = { u '70303660': { u 'title': u 'The Forbidden Feast', u 'synopsis': u 'Caster and Uryu discuss their views on God, resulting in plans for a horrifying attack -- one that requires everyone else to unite against Caster.', u 'summary': { u 'notStreaming': False, u 'isOriginal': False, u 'season': 1, u 'idx': 13, u '$type': u 'leaf', u 'type': u 'episode' }, }, u '70303654': { u 'title': u 'Dark Forest', u 'synopsis': u 'The battle is on hold as the group decides what to do about Ryunosuke Uryu and his servant, Caster, who have been kidnapping and sacrificing children.', u 'summary': { u 'notStreaming': False, u 'isOriginal': False, u 'season': 1, u 'idx': 7, u '$type': u 'leaf', u 'type': u 'episode' }, }, } 

So far I have tried:

sorted(episodes, lambda x: x['summary']['idx']) 

1 Answer 1

3

You need to iterate over the sub-dictionaries, rather than the episode keys..

sorted(episodes.values(), key=lambda x: x['summary']['idx']) 

(By default, iterating a dictionary directly iterates through its keys, not its values.)

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

2 Comments

I get the following exception when trying that: >>> sorted(episodes.values(), key=lambda x: x['summary']['idx']) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: 'int' object is not subscriptable`
Oh, sorry, should include key=.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.