Paul K.
Paul K.

Reputation: 11

How to sort based on a nested value?

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

Answers (1)

John Zwinck
John Zwinck

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

Related Questions