0

I created a dictionary:

listing = {'2': 'Mary Lejam', '3': 'Zachery Aka', '1': 'John Joer', '4': 'Joe Private', '10': 'Carla Chris'}

I'm writing a simple program that sorts the names according to the keys (which are the id) and sort according to last name I figure out the id one with the keys of the dictionary. But now i'm trying to find a way to sort the last name.

  1. if i do listing.values(), it sorts with the first letter of the first name
  2. if i use the itemgetter, i can only put an index that it will sort with.

I tried importing re, such as itemgetter(re.match(regex)), gives me error I was wondering if it is possible to use itemgetter and write some regex inside it to ignore everything before the last name. It would ignore everything before the space basically.

LastName = sorted(listing.values(), key=itemgetter(Some Regex))
Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
Ding Ma
  • 11
  • 4

2 Answers2

0

One way is to split and reassemble:

listing = {'2': 'Mary Lejam', '3': 'Zachery Aka', '1': 'John Joer', '4': 'Joe Private', '10': 'Carla Chris'}

import operator
sorted(({k:[v.split(' ')[1], v.split(' ')[0]] for k,v in listing.items()}).items(), key=operator.itemgetter(1))

[('3', ['Aka', 'Zachery']),
 ('10', ['Chris', 'Carla']),
 ('1', ['Joer', 'John']),
 ('2', ['Lejam', 'Mary']),
 ('4', ['Private', 'Joe'])]

listing = {i[0]:' '.join([i[1][1], i[1][0]]) for i in temp}

{'3': 'Zachery Aka',
 '10': 'Carla Chris',
 '1': 'John Joer',
 '2': 'Mary Lejam',
 '4': 'Joe Private'}

But in general Python dictionaries are unsorted, if you really need a sorted data structure you shouldn't be using a dict.

Josh Friedlander
  • 10,870
  • 5
  • 35
  • 75
0

itemgetter isn't particularly useful here, because you need to do further work on the return value, and Python doesn't have any way to compose functions directly.

sorted(listing.items(), key=lambda x: x[1].split()[1])

If there were function composition, say, because you are using the toolz package, you might write

from toolz import compose

# Equivalent functions, but names reflect different *purposes*
get_name = get_last_name = itemgetter(1)
split_name = methodcaller('split')

sorted(listing.items(), key=compose(get_last_name, split_name, get_name))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Did you mean `x['1']` instead of `x[1]`? – kojiro Feb 24 '19 at 16:40
  • 1
    No, because `x` here is a tuple like `('1', 'John Joer')`. `x[1]` is the last name in the tuple. – chepner Feb 24 '19 at 16:42
  • Thank you!, So if i understand correctly, the values of the dictionary is composed of tuple and i can get the index 1 of the tuple which represent the last name – Ding Ma Feb 24 '19 at 17:36
  • Not the dictionary itself; the iterator returned by `listing.items()`. If you used `sorted(listing)`, you would just get back the list of sorted *keys*. – chepner Feb 24 '19 at 19:49