[英]Order a list of dictionaries based on another dictionary
我有這樣的字典,以穩定月份的順序:
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']]))
使用排序鍵功能查找月份:
def sort_by_month(entry):
return meses_ord[entry['month']]
sorted(fechas_, key=sort_by_month)
sort函數也可以表示為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'}]
假設您已如下定義變量
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 Wiki和Python文檔中找到更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.