Python itemgetter根据值字符串的中间对dict排序

时间:2019-02-24 16:27:41

标签: python

我创建了字典:

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

我正在编写一个简单的程序,该程序根据键(即id)对名称进行排序,并根据姓氏进行排序 我用字典的键找出id。但是现在我正在尝试寻找一种对姓氏进行排序的方法。

  1. 如果我执行listing.values(),它将以名字的首字母排序
  2. 如果我使用itemgetter,则只能放置一个将与之排序的索引。

我尝试导入re,例如itemgetter(re.match(regex)),但出现错误 我想知道是否有可能使用itemgetter并在其中写入一些正则表达式来忽略姓氏之前的所有内容。它将基本上忽略掉空格之前的所有内容。

LastName = sorted(listing.values(), key=itemgetter(Some Regex))

2 个答案:

答案 0 :(得分:0)

一种方法是拆分和重新组装:

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'}

但是一般来说Python dictionaries are unsorted,如果您确实需要排序的数据结构,则不应该使用字典。

答案 1 :(得分:0)

itemgetter在这里并不是特别有用,因为您需要对返回值做进一步的工作,并且Python无法直接构成函数。

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

如果有 函数组成,例如,因为您使用的是toolz包,则可以编写

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))
相关问题