0

Have a list of dict objects where 50% will have a key name and 50% will have a key full_name and I'd like it sorted alphabetically based on either key.

Some sort function like:

if 'name' in a:
    a_name = a['name']
elif 'full_name' in a:
    a_name = a['full_name']
# repeat with a b in the compare, sort based on value

Is there a more efficient way here?

Wells
  • 10,415
  • 14
  • 55
  • 85
  • 2
    That’s not really a duplicate of this. This one has the added complication that you need to select one of two keys. – Tom Zych Jan 30 '16 at 19:00
  • 1
    @Padraic Cunningham, IMHO, this is not a duplicate. The question you mentioned did tell about multiple keys, but this question is different. – Ahsanul Haque Jan 30 '16 at 19:04

3 Answers3

1

I think it should work:

sorts = sorted(data, key= lambda x: x.get('name') or x.get('full_name'))
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Concatenate both strings, substituting an empty string for the missing one:

lst.sort(key=lambda d: d.get('name', '') + d.get('full_name', ''))
Tom Zych
  • 13,329
  • 9
  • 36
  • 53
-1

Have you tried a lambda based functional approach:

testList = sorted(testList, key=lambda name: a_name['name'] if 'name'   in a_name else a_name['full_name'])