如何对比两个Python字典,匹配值后更新dict_2的键
Python字典键替换实现方案
首先先给出符合Python语法的输入字典示例(字符串类型的键值需要添加引号):
dict_1 = {"exam": "student", "test": "faculty"} dict_2 = { "s1": ["student as s", "advisor as a", "teacher as t"], "s2": ["faculty as fac", "marks as m"] }
核心实现逻辑
- 遍历
dict_1的键值对,作为替换映射规则 - 对
dict_2的每个值(列表),检查是否存在元素包含dict_1的取值 - 匹配成功后使用
dict_1对应的键作为新键,保留原dict_2的取值生成新字典
完整实现代码
new_dict = {} # 遍历dict_2的所有键值对 for old_key, value_list in dict_2.items(): # 遍历dict_1的匹配规则 for new_key, match_str in dict_1.items(): # 检查match_str是否存在于value_list的任意元素中 if any(match_str in item for item in value_list): new_dict[new_key] = value_list break # 替换原dict_2(如果需要保留原dict_2可以跳过这步) dict_2 = new_dict print(dict_2)
输出结果
{'exam': ['student as s', 'advisor as a', 'teacher as t'], 'test': ['faculty as fac', 'marks as m']}
内容的提问来源于stack exchange,提问作者Madhu
相关产品推荐
相关产品推荐

