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

Python中将指定字典值复制到新字典的最pythonic实现方式是什么

符合Pythonic规范的实现方案

核心思路是通过预定义键名映射表把字段对应关系和业务逻辑解耦,配合字典推导式实现简洁的取值+过滤+键替换逻辑:

# 定义原字典key到新字典key的映射,后续调整字段只需修改这个映射表
KEY_MAP = {
    "name": "customer_name",
    "email": "customer_email",
    # 可按需新增其他映射关系,比如 "phoneNumber": "customer_phone"
}

customer = [{
 'name': 'John',
 'email': 'johnsmith@gmail.com',
 'phoneNumber': '9999999',
 'country': 'USA',
 'city': None,
 'preferences': {}
}]

new_customer_dict = {}
for client in customer:
    new_customer_dict.update({
        new_key: client[old_key]
        for old_key, new_key in KEY_MAP.items()
        if client.get(old_key)
    })

如果确定customer列表始终只有1个元素,可直接用字典推导式生成结果:

new_customer_dict = {
    new_key: customer[0][old_key]
    for old_key, new_key in KEY_MAP.items()
    if customer[0].get(old_key)
}

方案说明

  • 过滤逻辑自动匹配需求:if client.get(old_key)会自动过滤所有Python假值,包含None、空字符串、空字典、空列表等,完全符合仅保留有效值的规则
  • 可维护性极强:新增/删除需要同步的字段时,只需要修改KEY_MAP即可,不需要改动业务逻辑代码
  • 无报错风险:用get()方法取值,原字典不存在对应key时会返回None被过滤规则排除,不会抛出KeyError

如果需要更精细的过滤规则(比如需要保留数值0,仅排除None、空字符串、空字典),可以用Python 3.8+支持的海象运算符优化判断逻辑:

new_customer_dict.update({
    new_key: val
    for old_key, new_key in KEY_MAP.items()
    if (val := client.get(old_key)) is not None and val != "" and val != {}
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:45:04