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

如何基于大小写不同的指定列表匹配字典列表生成新字典?

解决方案

可以通过忽略大小写的匹配逻辑结合字典推导式实现需求,步骤如下:

  1. 先将目标字段列表转换为小写集合,提升匹配效率
  2. 遍历字典列表,筛选出符合条件的键值对生成新字典

完整代码:

list_of_dicts = [   
{'fieldname': 'Id', 'source': 'microsoft', 'nullable': True, 'type': 'int'},
{'fieldname': 'FirstName', 'source': 'microsoft', 'nullable': True, 'type': 'string'},
{'fieldname': 'LastName', 'source': 'microsoft', 'nullable': False, 'type': 'string'},
{'fieldname': 'Address1', 'source': 'microsoft', 'nullable': False, 'type': 'string'}
                ]

fieldname_list = ['FIRSTNAME', 'LASTNAME']

# 转换为小写集合,统一匹配规则
target_fields = {field.lower() for field in fieldname_list}

# 字典推导式生成目标字典
new_dict = {item['fieldname']: item['type'] for item in list_of_dicts if item['fieldname'].lower() in target_fields}

print(new_dict)
# 输出结果: {'FirstName': 'string', 'LastName': 'string'}

逻辑说明

  • 用集合存储小写后的目标字段,是因为集合的成员查询操作(in)效率远高于列表,数据量大时优势更明显
  • 通过item['fieldname'].lower()将字典中的字段名转为小写,和目标集合中的元素进行匹配,实现大小写不敏感的筛选
  • 推导式中直接提取符合条件的fieldname作为键、type作为值,一步生成所需的新字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:05:19