这是我的字典架构。
f = { 'client_id': {'client_name': [{'transaction_date': date_time,
'transaction_amount': value_in_dollar}]
}
}
如何获得具有最低transaction_amount的字典。
输入示例:
f = { 905220: {'Steven Jhon': [{'transaction_date': '2016-05-07 00:00:00+00',
'transaction_amount': 1198},
{'transaction_date': '2016-05-08 00:00:00+00',
'transaction_amount': 4889}]
},
905221: {'Chris Chris': [{'transaction_date': '2016-05-01 00:00:00+00',
'transaction_amount': 50},
{'transaction_date': '2016-05-02 00:00:00+00',
'transaction_amount': 100},
{'transaction_date': '2016-05-03 00:00:00+00',
'transaction_amount': 10}]
}
}
期望的输出:
f = { 905220: {'Steven Jhon': [{'transaction_date': '2016-05-07 00:00:00+00',
'transaction_amount': 1198}]
},
905221: {'Chris Chris': [{'transaction_date': '2016-05-03 00:00:00+00',
'transaction_amount': 10}]
}
}
最佳答案
您可以使用大的dict理解力,或类似这样的辅助函数:
def get_min_by_value(x):
if isinstance(x, dict):
return {k: get_min_by_value(v) for k, v in x.items()}
elif isinstance(x, list):
return [min(x, key=lambda d: d['transaction_amount'])]
out = get_min_by_value(f)
关于python - 如何获得键值最低的字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37792901/