TiShow
TiShow

Reputation: 1014

How to rearrange double dictionary by value (Python3)

I'm a beginner coding. I'm struggling to rearrange double dictionary. For instance,

dict = {
'student_A': {
    'name': 'Hiro',
    'age': 22,
},
'student_B': {
    'name': 'Alex',
    'age': 24,
    },
'student_C': {
    'name': 'Jon',
    'age': 23,
    }
}

In this code, how can I line up by order of age like this ? :

[
 {
    'name': 'Alex'
 },
 {   
    'name': 'Jon'
 },
 {
    'name': 'Hiro'
 }
]

It would be greatly appreciated if you could explain the details !!

Upvotes: 2

Views: 100

Answers (2)

Sam Redway
Sam Redway

Reputation: 8127

It looks (from the output that you have given) like you actually want the name in reverse order of age? And you also want just the name in object which is listed - so you filter out the age part of the original object.

In this case you probably want to use a list comprehension which is an immensely useful and pythonic way to do filter and map type operations on a list. To find out more about list comprehension please check the official documentation.

An example of how to do this:

>>> my_ordered_list = [ {'name': student['name']} for student in sorted(dict.values(), key=lambda x:-x['age']) ]

>>> my_ordered_list
[{'name': 'Alex'}, {'name': 'Jon'}, {'name': 'Hiro'}]

Upvotes: 1

Pedro Castilho
Pedro Castilho

Reputation: 10522

You can do it like this:

value_list = list(dict.values())
value_list.sort(key=lambda value: value['age'])

This will make value_list a list of the values in the dictionary, sorted by age. You do this by getting a dict_values object by calling dict.values(). This object can then be converted into a list, which can then be sorted by calling the list.sort() method. The key parameter is a function which will return the age for each dictionary.

In case you haven't seen the lambda name: statement syntax, there's a reference here.

Upvotes: 1

Related Questions