Reputation: 11
Given the following dictionary, how can you sort the "namedir" list by the value assoicated with the nested "last" key? Also note that the last "name" entry does not have a "last" key or value, so I need to avoid missing key errors. Thanks!
{
"namedir": [
{
"name": {
"first": "joe",
"last": "jones"
}
},
{
"name": {
"first": "bob",
"last": "doe"
}
},
{
"name": {
"first": "pete",
"last": "doe"
}
},
{
"name": {
"first": "jane"
}
}
]
}
Upvotes: 0
Views: 24
Reputation: 249133
You can use a custom sort key to do this easily. You need to decide on a rule for what to do when there is no last name. I chose to treat a missing last name as an empty string, which means those entries come first.
sorted(namedir, key=lambda x: x['name'].get('last', ''))
That gives you:
[{'name': {'first': 'jane'}},
{'name': {'first': 'bob', 'last': 'doe'}},
{'name': {'first': 'pete', 'last': 'doe'}},
{'name': {'first': 'joe', 'last': 'jones'}}]
Upvotes: 1