如何基于大小写不同的指定列表匹配字典列表生成新字典?
解决方案
可以通过忽略大小写的匹配逻辑结合字典推导式实现需求,步骤如下:
- 先将目标字段列表转换为小写集合,提升匹配效率
- 遍历字典列表,筛选出符合条件的键值对生成新字典
完整代码:
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
相关产品推荐
相关产品推荐

