This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi everyone! I've been working on a project in Python lately and I've been absolutely stunned by its ability to handle data the way it does. I have a dict sorting question that I've been unable to really find through searches.
I need to sort the top level keys of a dict using 2 separate inner values from each top level value... am I even explaining that right... To better illustrate this I made an over simplified version here.
So what I would like is for something like this:
SeatingChart = {
"John":
{
"row": 2
"seat": 1
},
"Bob":
{
"row": 2
"seat": 2
},
"Alice":
{
"row": 1
"seat": 2
},
"Dave":
{
"row": 3
"seat": 2
},
"Jane":
{
"row": 3
"seat": 1
},
"Lily":
{
"row": 1
"seat": 1
},
"Steve":
{
"row": 4
"seat": 1
},
}
to be sorted first by "row" then by "seat" so the resulting printout of keys is like this:
OUTPUT >>> print(SortedKeys)
["Lily", "Alice", "John", "Bob", "Jane", "Dave", "Steve"]
Which essentially represents this data order:
{
"Lily":
{
"row": 1
"seat": 1
},
"Alice":
{
"row": 1
"seat": 2
},
"John":
{
"row": 2
"seat": 1
},
"Bob":
{
"row": 2
"seat": 2
},
"Jane":
{
"row": 3
"seat": 1
},
"Dave":
{
"row": 3
"seat": 2
},
"Steve":
{
"row": 4
"seat": 1
},
}
Currently I am only sorting by row which allows seats to be randomly mixed up within each row and that's not desired at all. Here's my code so far:
SortedKeys = sorted(SeatingChart, key=lambda x: SeatingChart[x]['row'])
Is there any way to also have the seat value sort within each row?
Sure this could be done using temporary dicts and iterating rows into indexes then sorting seats inside that and reassembling it all but I was hoping someone might be able to shine a more Pythonic light on this one.
Thank you for any time answering this :)
Subreddit
Post Details
- Posted
- 6 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnpython...