Python 2.7中如何按条件为字典添加指定字段(Pythonic写法)
更Pythonic的字典列表匹配更新方案
嘿,这个场景太常见了!你原来的嵌套循环虽然能工作,但确实不够优雅,而且数据量大的时候效率也不高。咱们用字典映射的方式来优化,既简洁又高效,完全符合Python风格。
核心思路
先把second列表转换成以full_name为键的字典,这样查找匹配项的时间复杂度从O(n)降到O(1),然后只需要遍历一次first列表就能完成所有更新。
实现代码
first = [ {'name': 'John', 'last_name': 'Doe', 'age':'27'}, {'name': 'Jack', 'last_name': 'Sparrow', 'age':'26'} ] second = [ {'full_name': 'John Doe', 'height':130}, {'full_name': 'Donkey Kong', 'height':156}, {'full_name': 'Jack Sparrow', 'height':180} ] # 用字典推导式把second转成快速查找的映射 full_name_map = {item['full_name']: item['height'] for item in second} # 遍历first列表,匹配后更新 for person in first: current_full_name = f"{person['name']} {person['last_name']}" if current_full_name in full_name_map: person['height'] = full_name_map[current_full_name] # 查看更新后的结果 print(first)
扩展支持多字段更新
如果以后需要添加更多字段(比如体重、国籍之类的),只需要稍微调整映射的结构,把整个字典存进去,就能一次性提取多个字段,可读性拉满:
# 存储完整的字典条目,方便后续提取多个字段 full_name_full_map = {item['full_name']: item for item in second} for person in first: current_full_name = f"{person['name']} {person['last_name']}" if current_full_name in full_name_full_map: matched_data = full_name_full_map[current_full_name] person['height'] = matched_data['height'] # 可以轻松添加更多字段 # person['some_other_field'] = matched_data['some_other_field']
为什么这更Pythonic?
- 高效:时间复杂度从原来的O(n*m)降到O(n+m),数据量越大优势越明显
- 可读:代码逻辑清晰,一眼就能看明白是先做映射再匹配更新
- 可扩展:后续加字段或者修改匹配规则,只需要调整映射和更新部分,不需要改嵌套循环
内容的提问来源于stack exchange,提问作者Moshe Davidi
相关产品推荐
相关产品推荐

