如何获取嵌套字典中第n大price值的对应键?含缺失值高效处理
处理嵌套字典缺失price值时获取第n大price对应键的方案
方案一:先过滤有效条目再排序
直接排除没有price键的条目,只对有有效价格数据的条目排序,既避免KeyError,又减少排序数据量,效率更高:
my_dict = {'0': {'name': 'A', 'price': 50}, '1': {'name': 'B', 'price': 20}, '2': {'name': 'C'}, '3': {'name': 'D', 'price': 10}} number_im_using_to_find = 2 # 要找第2大的price对应的name # 过滤出包含price键的条目 valid_entries = [item for item in my_dict.items() if 'price' in item[1]] if not valid_entries: print("无有效price数据") else: # 按price升序排序 sorted_entries = sorted(valid_entries, key=lambda x: x[1]['price']) # 倒数第n个即为第n大的条目 target = sorted_entries[-number_im_using_to_find] print(target[1]['name']) # 输出:B
方案二:给缺失price设置默认值参与排序
如果不想过滤缺失price的条目,而是将其视为特定值(最小/最大)参与排序,可用dict.get()方法设置默认值,避免报错:
- 将缺失price视为最小值(用
float('-inf'),排序时排在最前面):
my_dict = {'0': {'name': 'A', 'price': 50}, '1': {'name': 'B', 'price': 20}, '2': {'name': 'C'}, '3': {'name': 'D', 'price': 10}} number_im_using_to_find = 2 sorted_entries = sorted(my_dict.items(), key=lambda x: x[1].get('price', float('-inf'))) target = sorted_entries[-number_im_using_to_find] print(target[1]['name']) # 输出:B
- 将缺失price视为最大值(用
float('inf'),排序时排在最后面):
sorted_entries = sorted(my_dict.items(), key=lambda x: x[1].get('price', float('inf'))) target = sorted_entries[-number_im_using_to_find] # 若number_im_using_to_find=1,会输出缺失price的C
效率说明
- 方案一提前过滤无效条目,数据量大时排序速度更快,是更高效的选择;
- 方案二更灵活,适合需要保留所有条目排序逻辑的场景。
内容的提问来源于stack exchange,提问作者dez8686
相关产品推荐
相关产品推荐

