访问变量字典名称的 Python 3x 字典值
Accessing Python 3x dictionary values for a variable dictionary name
我有一个 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,897 kg',
'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']
你可以这样做:
import specs
specs.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'}
specs.f150['horsepower']
# '385 to 475 hp'
你可以使用
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,897 kg',
'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')
我有一个 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,897 kg',
'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']
你可以这样做:
import specs
specs.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'}
specs.f150['horsepower']
# '385 to 475 hp'
你可以使用
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,897 kg',
'horsepower' : '290 to 450 hp',
'engine' : '6.2 L V8, 6.7 L V8 diesel, 7.3 L V8'
}}}
然后你可以像这样使用:
specs.cars[carmodel]['horsepower']
您可以使用 getattr
import specs
getattr(specs, 'f150')