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

Python技术问询:如何对比列表与字典的键并返回对应值存入列表

解决方法:匹配列表日期与字典键获取对应ID

嘿,这个需求其实很容易实现,我给你几种实用的方式,你可以根据自己的场景选:

1. 简洁的列表推导式

这是Python里最常用的写法,一行就能搞定,适合你确定列表里的所有日期都能在字典里找到的情况:

birthday_persons = ['1966-06-26T11:50:25.558Z', '1949-10-09T00:25:51.304Z']
dates_ids = {'1966-06-26T11:50:25.558Z': 1, '1949-10-09T00:25:51.304Z': 2, '1992-11-21T06:28:32.563Z': 3}

# 获取匹配的ID列表
matched_ids = [dates_ids[date] for date in birthday_persons]
print(matched_ids)  # 输出: [1, 2]

2. 带存在性判断的版本(避免KeyError)

如果不确定列表里的所有日期都在字典里,怕出现报错,那就加上判断,或者用字典的get()方法来安全获取:

方法A:加条件判断的列表推导式

matched_ids = [dates_ids[date] for date in birthday_persons if date in dates_ids]

这样只会返回字典里存在的日期对应的ID,不存在的会直接跳过。

方法B:用get()方法返回默认值

如果想给不存在的日期设置一个默认值(比如None),可以这么写:

matched_ids = [dates_ids.get(date, None) for date in birthday_persons]

比如如果列表里有个不在字典的日期,就会返回None,不会触发报错。

3. 新手友好的循环遍历写法

如果你刚学Python,想更清晰地看到每一步的逻辑,用普通循环也完全没问题:

matched_ids = []
for date in birthday_persons:
    if date in dates_ids:
        matched_ids.append(dates_ids[date])
print(matched_ids)  # 输出: [1, 2]

这几种方式都能满足你的需求,选最适合自己代码风格的就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:37:39