python从嵌套字典中获取最小/最大值

时间:2016-04-29 08:51:04

标签: python dictionary

如何从嵌套字典中获取最小值/最大值,该字典也包含' Nan'缺少值?

*这是供参考我找到了解决方案,我想我会在这里分享它,因为我无法在stackoverflow上的任何地方找到答案。

示例数据集(我正在使用安然数据集):

  

{' METTS MARK':{'薪水':365788,' to_messages':807,   ' deferral_payments':' NaN',' total_payments':1061827,   ' exercised_stock_options' NaN' ,'奖金':600000,...

2 个答案:

答案 0 :(得分:2)

来自udacity论坛,很好的解决方案

exercised_stock_options = [item["exercised_stock_options"] for k, item in 
data_dict.iteritems() if not item["exercised_stock_options"] == "NaN"]
print "min is %s" % min(exercised_stock_options)
print "max is %s" % max(exercised_stock_options)

答案 1 :(得分:1)

这就是我解决这个问题的方法:

#get minimum and maximum stock options

result = min(data_dict.values(), key=lambda v:v['exercised_stock_options'] if v['exercised_stock_options'] != 'NaN' else float('inf'))
print result

result = max(data_dict.values(), key=lambda v:v['exercised_stock_options'] if v['exercised_stock_options'] != 'NaN' else float('-inf'))
print result