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

如何实现字典列表条件追加:依据object值大小写添加新键值对

解决思路与实现代码

核心逻辑拆解

  1. 判断条件:用字符串的isupper()方法检测object字段是否为全大写
  2. 统一操作:无论object是大写还是小写,都需要将category字段转为小写
  3. 条件操作:仅当object为全大写时,向字典添加new_object键,值为object的小写形式

实现方式一:for循环(直观易读)

这种方式逻辑清晰,适合理解调试,推荐复制字典操作避免破坏原数据:

original_list = [{'object':'Apple','category':'Fruit'}, {'object':'cat', 'category':'Aquatic'},{'object':'FISH','category':'Animal'}]
result_list = []

for item in original_list:
    # 复制原字典,避免修改原始数据
    new_item = item.copy()
    # 统一转换category为小写
    new_item['category'] = new_item['category'].lower()
    # 判断object是否全大写,满足则添加new_object字段
    if new_item['object'].isupper():
        new_item['new_object'] = new_item['object'].lower()
    result_list.append(new_item)

print(result_list)

实现方式二:字典推导式(简洁高效)

用列表推导式嵌套字典展开语法,一行完成逻辑:

original_list = [{'object':'Apple','category':'Fruit'}, {'object':'cat', 'category':'Aquatic'},{'object':'FISH','category':'Animal'}]

result_list = [
    {**item, 'category': item['category'].lower(), 'new_object': item['object'].lower()} 
    if item['object'].isupper() 
    else {**item, 'category': item['category'].lower()}
    for item in original_list
]

print(result_list)

关键说明

  • isupper()方法:精准判定字符串是否为全大写(像'Apple'这种首字母大写的不会被判定,符合需求)
  • 字典复制:item.copy()或{**item}都是为了避免直接修改原列表中的字典,防止后续操作影响原始数据
  • 两种方式都能输出你需要的结果,可根据代码风格偏好选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:12:38