Python字典列表值匹配:替换devices值为alldicts对应匹配键
字典列表结构保留与值替换问题
问题背景
给定两个字典列表:
devices = [ {'a': 'b', 'c': 'd'}, {'a': 'e', 'f': 'g'}, {'h': 'i', 'j': 'k'} ]
alldicts = [ {'a': {'eth1': 'b', 'eth2': 'e'}}, {'c': {'eth1': 'd', 'eth2': 'o', 'eth3': 'q'}}, {'f': {'eth1': 'g'}}, {'h': {'eth1': 'i'}}, {'j': {'eth1': 'k'}} ]
需求:生成一个新的字典列表,完全保留devices的结构,但将每个字典中的值替换为alldicts中对应顶级键下、匹配该值的子字典键(比如devices中第一个字典的'a':'b',对应alldicts里'a'下'b'对应的键'eth1')。
期望输出:
final_list = [ {'a': 'eth1', 'c': 'eth1'}, {'a': 'eth2', 'f': 'eth1'}, {'h': 'eth1', 'j': 'eth1'} ]
用户尝试的代码(未得到期望结果):
final_int = [] for each in devices: for i,j in each.items(): for each_dict in alldicts: for k,l in each_dict.items(): for a,b in l.items(): if b == j and i == k: final_int.append({i:a})
问题分析
原代码的问题在于:每次匹配到对应关系时,会把单个键值对(比如{'a':'eth1'})单独加入结果列表,破坏了devices中原有的字典结构,最终得到的是一堆零散的单键字典,而非和原结构一致的多键字典。同时多层嵌套循环效率较低,我们可以先预处理alldicts为更易查询的结构,再遍历生成结果。
解决方案
步骤1:预处理查询字典
先把alldicts转换成一个反向查询字典,让我们可以通过顶级键+对应值快速找到目标eth标识:
# 构建查询映射:{顶级键: {值: eth键}} lookup_map = {} for item in alldicts: # 每个item只有一个顶级键,直接取出 top_key, sub_dict = next(iter(item.items())) # 反转子字典,值作为键,eth键作为值 lookup_map[top_key] = {v: k for k, v in sub_dict.items()}
步骤2:遍历生成结果
遍历devices中的每个字典,为每个字典创建一个新的临时字典,填充替换后的键值对,最后加入结果列表:
final_list = [] for dev_dict in devices: new_dict = {} for key, val in dev_dict.items(): # 通过查询映射直接获取对应的eth键 new_dict[key] = lookup_map[key][val] final_list.append(new_dict)
完整代码
devices = [ {'a': 'b', 'c': 'd'}, {'a': 'e', 'f': 'g'}, {'h': 'i', 'j': 'k'} ] alldicts = [ {'a': {'eth1': 'b', 'eth2': 'e'}}, {'c': {'eth1': 'd', 'eth2': 'o', 'eth3': 'q'}}, {'f': {'eth1': 'g'}}, {'h': {'eth1': 'i'}}, {'j': {'eth1': 'k'}} ] # 构建查询映射 lookup_map = {} for item in alldicts: top_key, sub_dict = next(iter(item.items())) lookup_map[top_key] = {v: k for k, v in sub_dict.items()} # 生成结果 final_list = [] for dev_dict in devices: new_dict = {} for key, val in dev_dict.items(): new_dict[key] = lookup_map[key][val] final_list.append(new_dict) # 验证输出 print(final_list)
运行后输出与期望完全一致:
[{'a': 'eth1', 'c': 'eth1'}, {'a': 'eth2', 'f': 'eth1'}, {'h': 'eth1', 'j': 'eth1'}]
内容的提问来源于stack exchange,提问作者kryton007
相关产品推荐
相关产品推荐

