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

Python字典转双引号格式时如何将数值也用双引号包裹

问题说明

我从接收的响应数据中构建了一个字典,需要将包含数字的字段值也放置在双引号内。
当前字典示例:

{'id': '262', 
'model_name': 'string', 
'endpoint_name': 'string', 
'data_capture_location': 'string', 
'baseline_job_output_location': 'string', 
'monitoring_output_location': 'string', 
'schedule_expression': 'cron(0 0/23 ? * * *)', 
'instance_type': 'string', 
'instance_volume_size': 20, 
'baseline_max_runtime_seconds': 3600, 
'monitor_max_runtime_seconds': 3600, 
'pipeline_type': 'byom_data_quality_monitor', 
'baseline_data': 'SageRltArtifacts/iris_binomial_baseline_DQ.csv'}

在将该字典传入对应函数前,需要将字典内所有单引号替换为双引号。尝试使用json.dump方法完成转换,但instance_volume_size、baseline_max_runtime_seconds、monitor_max_runtime_seconds这类数值类型的字段值也需要被双引号包裹,暂未找到可行的实现方案。

解决方法

json.dumps默认会保留数值类型,不会给数字值加双引号,只需要在序列化前把字典所有值统一转为字符串类型,再做序列化即可满足要求。

单层字典实现

直接用字典推导式遍历所有键值对,把值强转为字符串后再序列化:

import json

original_dict = {
    'id': '262', 
    'model_name': 'string', 
    'endpoint_name': 'string', 
    'data_capture_location': 'string', 
    'baseline_job_output_location': 'string', 
    'monitoring_output_location': 'string', 
    'schedule_expression': 'cron(0 0/23 ? * * *)', 
    'instance_type': 'string', 
    'instance_volume_size': 20, 
    'baseline_max_runtime_seconds': 3600, 
    'monitor_max_runtime_seconds': 3600, 
    'pipeline_type': 'byom_data_quality_monitor', 
    'baseline_data': 'SageRltArtifacts/iris_binomial_baseline_DQ.csv'
}

# 所有值统一转为字符串类型
formatted_dict = {key: str(value) for key, value in original_dict.items()}
# 序列化为双引号格式的JSON字符串
result = json.dumps(formatted_dict, indent=2)

输出结果中所有字段值(包括原数字类型字段)都会被双引号包裹,不存在Python字典默认的单引号,可直接传入目标函数使用。

嵌套字典扩展实现

如果字典存在多层嵌套结构,可以用递归方法统一转换所有层级的值:

def convert_all_value_to_str(input_obj):
    if isinstance(input_obj, dict):
        return {k: convert_all_value_to_str(v) for k, v in input_obj.items()}
    elif isinstance(input_obj, list):
        return [convert_all_value_to_str(item) for item in input_obj]
    else:
        return str(input_obj)

# 转换后再序列化即可
nested_result = json.dumps(convert_all_value_to_str(original_dict), indent=2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 03:39:43