Search code examples
pythonpython-3.xdictionarypython-module

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

Solution

  • 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']