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

Python3.6中能否将变量值作为字典值的一部分?

如何在Python字典的值中实现变量插入?

嘿,我明白你的问题了——你在用Python 3.6,熟悉字符串的.format()方法来插入变量,但尝试直接对字典调用这个方法时触发了AttributeError: 'dict' object has no attribute 'format'的错误,对吧?这很正常,因为.format()是字符串对象的专属方法,字典本身并没有这个属性。下面给你几种可行的替代方案:

方案1:逐个格式化字典的每个值

最直接的方式就是单独对字典里的每个字符串值调用.format(),把对应的变量传进去:

var_1 = "First_Var"
var_2 = "Second_Var_{}".format(var_1)
dict_with_inserts = {
    'First_Var': '{}_inserted'.format(var_1),
    'Second_Var': '{}_inserted'.format(var_2)
}
print(dict_with_inserts)

运行后输出:

{'First_Var': 'First_Var_inserted', 'Second_Var': 'Second_Var_First_Var_inserted'}

方案2:用字典推导式批量处理

如果你的字典条目比较多,用字典推导式会更高效,还能让代码更简洁:

var_1 = "First_Var"
var_2 = "Second_Var_{}".format(var_1)
# 先定义原始的带占位符的字典
original_dict = {'First_Var': '{}_inserted', 'Second_Var': '{}_inserted'}
# 遍历字典,根据key匹配对应的变量来格式化值
dict_with_inserts = {
    key: value.format(var_1 if key == 'First_Var' else var_2) 
    for key, value in original_dict.items()
}
print(dict_with_inserts)

方案3:用Python 3.6+的f-string(更简洁)

既然你用的是Python 3.6,完全可以利用f-string来实现变量插入,写法会更直观:

var_1 = "First_Var"
var_2 = f"Second_Var_{var_1}"  # 这里先用f-string生成var_2
dict_with_inserts = {
    'First_Var': f"{var_1}_inserted",
    'Second_Var': f"{var_2}_inserted"
}
print(dict_with_inserts)

这几种方法都能实现你想要的效果,你可以根据自己的代码场景选择最适合的一种~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:58:07