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

Python字典通过键取值时两种方法结果不一致的问题

问题解决:字典键匹配失败返回None的问题

问题背景

我有如下格式的Python字典:

py_dict = {
    "value": {
        'Timestamp(" "2020-04-05 02:48:00" ")': 699.0,
        'Timestamp(" "2020-06-26 07:36:00" ")': "nan",
        'Timestamp(" "2020-06-26 08:40:00" ")': 699.0,
     }
}   

(注:原代码中的"是HTML转义字符,对应Python中的双引号")

我通过datetime.strptime()提取并筛选有效时间戳键,找到最新时间戳:

from datetime import datetime

timestamps = {
    datetime.strptime(key.strip('Timestamp(" ').strip(' ")'), "%Y-%m-%d %H:%M:%S"): value
    for key, value in py_dict["value"].items()
    if value != "nan"
}

# 获取最新时间戳
latest_timestamp = max(timestamps)
# 返回结果:datetime.datetime(2020, 6, 26, 8, 40)

接着将datetime对象转换成字典的键格式:

formatted_latest_timestamp_key = (
    'Timestamp(" "' + latest_timestamp.strftime("%Y-%m-%d %H:%M:%S") + '" ")' 
)
# 返回结果:'Timestamp(" "2020-06-26 08:40:00" ")'

但调用dict.get()时传入该格式化键却返回None:

latest_price = py_dict["value"].get(f'"{formatted_latest_timestamp_key}"')
# 返回None

硬编码键能正常获取价格,Python版本为3.10.12,该如何解决?

问题原因

你在调用get()时给格式化后的键多套了一层双引号",而字典中实际的键并没有这层外层引号。生成的formatted_latest_timestamp_key已经是符合要求的键字符串,但f'"{...}"'把它包裹成了带外层引号的新字符串,和字典中的键完全不匹配,因此返回None。

解决方法

直接使用生成的formatted_latest_timestamp_key作为参数传入get()即可:

latest_price = py_dict["value"].get(formatted_latest_timestamp_key)
# 返回结果:699.0

额外优化建议

  1. 简化键解析逻辑:无需多次调用strip,利用固定格式拆分字符串更可靠:
# 替换原解析逻辑
datetime.strptime(key.split('" "')[1], "%Y-%m-%d %H:%M:%S")

键的格式固定为Timestamp(" "时间字符串" "),通过split('" "')分割后,索引1的位置就是目标时间字符串。

  1. 节省内存的写法:无需生成完整字典,遍历过程中直接记录最新时间戳和对应价格:
latest_timestamp = None
latest_price_val = None

for key, value in py_dict["value"].items():
    if value == "nan":
        continue
    ts = datetime.strptime(key.split('" "')[1], "%Y-%m-%d %H:%M:%S")
    if latest_timestamp is None or ts > latest_timestamp:
        latest_timestamp = ts
        latest_price_val = value

print(latest_price_val)  # 输出:699.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:23:10