MiniG34
MiniG34

Reputation: 332

Accessing Python 3x dictionary values for a variable dictionary name

I have a Python 3.7.3 file, specs.py, containing multiple dictionaries with the same keys.

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'
}

In another file, I am importing specs.py and would like to be able to find the value associated with a given key for the variable carmodel.

hp = specs.{what should I put here so it equals cardmodel}.['horsepower']

Upvotes: 1

Views: 51

Answers (3)

Iain Shelvington
Iain Shelvington

Reputation: 32294

You can reference any attribute of any object (modules are objects too) by string in python using getattr

import specs
getattr(specs, 'f150')

Upvotes: 1

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96246

you can use

getattr(specs, carmodel)['horsepower']

Because global variables will be attributes on a module object.

But it would make more sense maybe to nest your dict further:

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'
}}}

Then you can use like:

specs.cars[carmodel]['horsepower']

Upvotes: 1

oppressionslayer
oppressionslayer

Reputation: 7224

You can do this like this:

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'

Upvotes: 0

Related Questions