访问Python 3x字典值作为变量字典名称

我有一个Python 3.7.3文件specs.py,其中包含多个具有相同键的字典。

f150 = {
    'towing-capacity' : '3,402 to 5,897 kg','horsepower' : '385 to 475 hp','engine' : ' 2.7 L V6,3.3 L V6,3.5 L V6,5.0 L V8'
}

f250 = {
    'towing-capacity' : '5,670 to 5,'horsepower' : '290 to 450 hp','engine' : '6.2 L V8,6.7 L V8 diesel,7.3 L V8'
}

在另一个文件中,我正在导入specs.py,并希望能够找到与变量carmodel的给定键关联的值。

hp = specs.{what should I put here so it equals cardmodel}.['horsepower']
jianjunliqi 回答:访问Python 3x字典值作为变量字典名称

您可以使用

getattr(specs,carmodel)['horsepower']

因为全局变量将是模块对象上的属性。

但是可能更有意义的是嵌套您的字典:

cars = {
'f150': {
    'towing-capacity' : '3,402 to 5,897 kg','horsepower' : '385 to 475 hp','engine' : ' 2.7 L V6,3.3 L V6,3.5 L V6,5.0 L V8'
},'f250' : {
    'towing-capacity' : '5,670 to 5,'horsepower' : '290 to 450 hp','engine' : '6.2 L V8,6.7 L V8 diesel,7.3 L V8'
}}}

然后您可以像这样使用

specs.cars[carmodel]['horsepower']
,

您可以使用getattr在python中通过字符串引用任何对象的任何属性(模块也是对象)

import specs
getattr(specs,'f150')
,

您可以这样做:

import specs
specs.f150                                                                                                                                                                          

#{'towing-capacity': '3,# 'horsepower': '385 to 475 hp',# 'engine': ' 2.7 L V6,5.0 L V8'}

specs.f150['horsepower']                                                                                                                                                            
# '385 to 475 hp'
本文链接:https://www.f2er.com/2875375.html

大家都在问