根据另一本词典排列词典列表

2024-10-03 11:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典,用来确定月份的顺序:

meses_ord = {'January':1, 'February': 2, 'March':3, ... }

我也有这样一个字典列表:

fechas_ = [{'anyo': 2010, 'horas': Decimal('52.5'), 'month': 'March', 'importe': Decimal('4200.000')},
{'anyo': 2010, 'horas': Decimal('40.0'), 'month': 'February', 'importe':Decimal('3200.000')},
{'anyo': 2010, 'horas': Decimal('42.5'), 'month': 'April', 'importe': Decimal('3400.000')},
{'anyo': 2010, 'horas': Decimal('20.0'), 'month': 'January', 'importe': Decimal('1600.000')}]

我想按月份键排列字典表。你知道吗

我试过很多东西,但都没有成功:

fechas_ord = sorted(fechas_, key=operator.itemgetter(meses_ord[fechas_['mes']]))

Tags: 列表字典顺序decimalmarch月份monthord
2条回答

假设您定义了如下变量

months = {'January':1, 'February': 2, 'March':3, 'April':4 }
stuff = [{'anyo': 2010, 'horas': Decimal('52.5'), 'month': 'March', 'importe': Decimal('4200.000')},
{'anyo': 2010, 'horas': Decimal('40.0'), 'month': 'February', 'importe':Decimal('3200.000')},
{'anyo': 2010, 'horas': Decimal('42.5'), 'month': 'April', 'importe': Decimal('3400.000')},
{'anyo': 2010, 'horas': Decimal('20.0'), 'month': 'January', 'importe': Decimal('1600.000')}]

然后运行以下命令将返回一个排序的列表

sorted(stuff, key=lambda stuffa: months[stuffa['month']])

你可以在Python WikiPython documentation找到更多信息

使用排序键函数查找月份:

def sort_by_month(entry):
    return meses_ord[entry['month']]

sorted(fechas_, key=sort_by_month)

排序函数也可以表示为lambda,只需确保它接受一个参数:

sorted(fechas_, key=lambda entry: meses_ord[entry['month']])

演示:

>>> from decimal import Decimal
>>> from pprint import pprint
>>> meses_ord = {'January': 1, 'February': 2, 'March': 3, 'April': 4}
>>> fechas_ = [{'anyo': 2010, 'horas': Decimal('52.5'), 'month': 'March', 'importe': Decimal('4200.000')},
... {'anyo': 2010, 'horas': Decimal('40.0'), 'month': 'February', 'importe':Decimal('3200.000')},
... {'anyo': 2010, 'horas': Decimal('42.5'), 'month': 'April', 'importe': Decimal('3400.000')},
... {'anyo': 2010, 'horas': Decimal('20.0'), 'month': 'January', 'importe': Decimal('1600.000')}]
>>> pprint(sorted(fechas_, key=lambda entry: meses_ord[entry['month']]))
[{'anyo': 2010,
  'horas': Decimal('20.0'),
  'importe': Decimal('1600.000'),
  'month': 'January'},
 {'anyo': 2010,
  'horas': Decimal('40.0'),
  'importe': Decimal('3200.000'),
  'month': 'February'},
 {'anyo': 2010,
  'horas': Decimal('52.5'),
  'importe': Decimal('4200.000'),
  'month': 'March'},
 {'anyo': 2010,
  'horas': Decimal('42.5'),
  'importe': Decimal('3400.000'),
  'month': 'April'}]

相关问题 更多 >