Skip to main content
 首页 » 编程设计

python之在 python 中用变量填充字典的优雅方法

2025年05月04日21linjiqin

我正在寻找一种更优雅、更通用的方法来用变量填充字典:

dic = {} 
fruit = 'apple' 
vegetable = 'potato' 
 
dic['fruit'] = fruit 
dic['vegetable'] = vegetable 

有没有不使用引号中的变量名的更通用的方法?

请您参考如下方法:

如果引号有问题,这个怎么样?

fruit = 'apple' 
vegetable = 'potato' 
 
dic = dict( 
    fruit = fruit, 
    vegetable = vegetable 
)