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

Python如何打印嵌套字典中properties的无引号键及对应值到单行

问题原因

你当前的代码只提取了properties字典的键进行拼接,没有把对应的值拼接进去,而且不需要遍历外层data的键,直接定位到properties字典即可。

解决代码

易读写法

# 直接定位到properties字典
props = data["n"]["properties"]
output_parts = []

for key, val in props.items():
    # 字符串类型的值加双引号,其余类型直接转字符串
    if isinstance(val, str):
        val_str = f'"{val}"'
    else:
        val_str = str(val)
    output_parts.append(f"{key} : {val_str}")

# 拼接所有片段后打印
print(", ".join(output_parts))

单行简写写法

print(", ".join(f'{k} : "{v}"' if isinstance(v, str) else f"{k} : {v}" for k, v in data["n"]["properties"].items()))

输出效果

运行上述代码后即可得到你需要的结果:

date : 20141023, amount : 3890.36, currency : "USD", time : "6:09"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:54:00