首页 > 解决方案 > 在 Python 中循环导入字典

问题描述

我的问题与此有关。我有一个config_file由字典组成,如下所示:

config_1 = {
    'folder': 'raw1',
    'start_date': '2019-07-01'
}
config_2 = {
    'folder': 'raw2',
    'start_date': '2019-08-01'
}
config_3 = {
    'folder': 'raw3',
    'start_date': '2019-09-01'
}

然后我有一个单独的 python 文件来导入每个配置并做一些事情:

from config_file import config_1 as cfg1
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg2
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg3
Do some stuff using 'folder' and 'start_date'

我想把它放在一个循环中,而不是让它在 python 文件中列出 3 次。我怎样才能做到这一点?

标签: pythonpython-import

解决方案


如果我正确理解您的问题,请使用importlib。简而言之,您在 python 中编写的内容如下:

from package import module as alias_mod

在 importlib 中它变成:

alias_mod = importlib.import_module('module', 'package')

或者,等效地:

alias_mod = importlib.import_module('module.package')

例如:

from numpy import random as rm

在导入库中:

rm = importlib.import_module('random', 'numpy')

另一个有趣的事情是这篇文章中提出的这段代码,它不仅可以让你导入模块和包,还可以直接导入函数等等:

def import_from(module, name):
    module = __import__(module, fromlist=[name])
    return getattr(module, name)

对于您的特定情况,此代码应该可以工作:

import importlib

n_conf = 3
for in range(1, n_conf)
    conf = importlib.import_module('config_file.config_'+str(i))
    # todo somethings with conf 

但是,如果我能给您一些建议,我认为对您来说最好的办法是构建一个 json 配置文件并读取该文件,而不是导入模块。舒服多了。例如,在您的情况下,您可以创建config.json如下文件:

{
    "config_1": {
        "folder": "raw1",
        'start_date': '2019-07-01'
    },
    "config_2": {
        'folder': 'raw2',
        'start_date': '2019-08-01'
    },
    "config_3": {
        'folder': 'raw3',
        'start_date': '2019-09-01'
    }
}

读取json文件如下:

import json
with open('config.json') as json_data_file:
    conf = json.load(json_data_file)

现在您在内存中有一个简单的 python 字典,其中包含您感兴趣的配置设置:

conf['config_1']
# output: {'folder': 'raw1', 'start_date': '2019-07-01'}

推荐阅读