You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何获取字典中'c'键值大于给定值且最接近的项?

问题描述

现有如下结构的嵌套字典:

data = {
    '111': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 301},
    '112': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 302},
    '113': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 377},
    '114': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 311},
    '115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314},
    '116': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 306},
    '117': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 387}
    #...
}

需求:传入一个数值(例如312),返回对应的父字典项,要求满足:

  • 子字典的c值必须大于输入值
  • 在所有符合条件的项中,c值最接近输入值
  • 忽略c值小于等于输入值的项(比如114的c值311虽接近312,但因小于输入值被排除)

示例:输入312时,预期返回:

{'115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314}}
解决方案

可以通过以下步骤实现:

  • 筛选出所有c值大于输入值的项
  • 从筛选结果中找出c值与输入值差值最小的项
  • 将选中的项整理成目标字典格式

对应的Python代码如下:

def find_closest_greater(data, target):
    # 筛选符合条件的候选项:c值大于目标值
    candidates = [(key, value) for key, value in data.items() if value['c'] > target]
    if not candidates:
        return {}  # 无符合条件项时返回空字典
    
    # 按c值与目标值的差值排序,取差值最小的项
    closest_key, closest_value = min(candidates, key=lambda x: x[1]['c'] - target)
    return {closest_key: closest_value}

# 测试示例
data = {
    '111': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 301},
    '112': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 302},
    '113': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 377},
    '114': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 311},
    '115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314},
    '116': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 306},
    '117': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 387}
}

print(find_closest_greater(data, 312))
# 输出:{'115': {'a': 'xxxxxx', 'b': 'xxxxxx', 'c': 314}}

代码说明

  • 筛选候选项:通过列表推导式遍历原字典,仅保留c值大于目标值的键值对
  • 空值处理:若没有符合条件的项,返回空字典避免报错
  • 查找最接近项:利用min()函数,以c值与目标值的差值为排序依据(因只考虑大于的情况,差值均为正数,直接取最小即可)
  • 结果格式化:将选中的键值对重新包装成字典,匹配预期输出格式

内容的提问来源于stack exchange,提问作者Hugo Rieth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:10:34