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

如何筛选字典中值为多元素列表的键

筛选字典中值为多元素列表的键值对

示例原字典

dictX = {'cat': [0], 'dog': [1], 'bird': [2,2,2], 'fish': [3,4]}

解决方案

最简洁的方式是用字典推导式,一行代码就能完成筛选:

filtered_dict = {key: value for key, value in dictX.items() if len(value) > 1}

如果需要更直观的循环写法,也可以这样实现:

filtered_dict = {}
for key, value in dictX.items():
    # 只保留列表元素数量大于1的键值对
    if len(value) > 1:
        filtered_dict[key] = value

两种方法运行后,filtered_dict的结果都是:

{'bird': [2,2,2], 'fish': [3,4]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:42:33