How would I sort a dictionary of named dictionaries by a value in Python?

Question:

Here is an example of a list

accounts = {
     "user1": {
        "password": "test",
        "won": 8,
        "lost": 1,
        "colour": "green"
    },
    "user2": {
        "password": "test",
        "won": 12,
        "lost": 4,
        "colour": "blue"
    },
    "user3": {
        "password": "test",
        "won": 18,
        "lost": 1,
        "colour": "blue"
    }}

How would I go about sorting these by ‘won’?
I just cannot seem to figure it out.
Thanks!

Asked By: Knaifuu

||

Answers:

You can try using the sorted function with a custom key.

var = {"user2": {
        "password": "test",
        "won": 12,
        "lost": 4,
        "colour": "blue"
    },
    "user1": {
        "password": "test",
        "won": 8,
        "lost": 1,
        "colour": "green"
    },
    "user3": {
        "password": "test",
        "won": 18,
        "lost": 1,
        "colour": "blue"
    }}

result = sorted(var.items(),key=lambda x: x[1]["won"])
print(dict(result))

Output

{'user1': 
    {'password': 'test', 'won': 8, 'lost': 1, 'colour': 'green'}, 
'user2': 
    {'password': 'test', 'won': 12, 'lost': 4, 'colour': 'blue'}, 
'user3': 
    {'password': 'test', 'won': 18, 'lost': 1, 'colour': 'blue'}
}
Answered By: Alexander
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.