如何获得具有最低键值的字典

时间:2016-06-13 14:52:24

标签: python dictionary

这是我的字典架构。

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

1 个答案:

答案 0 :(得分:3)

你可以使用大字典理解,或者像这样的辅助函数:

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)