动态传递字典名称python

时间:2016-01-26 20:30:37

标签: python python-2.7 dictionary import

我有2个脚本,比如test.pymain.py 我的test.py只包含词典(没有其他代码)。

我通过传递dict_name作为参数来运行main.py。在这里,我想从test.py获取作为参数传递的dict,并在main.py中显示它的内容。

test.py

config_123={"name":"Dave","age":25}
config_89033 = {"name":"alex","age":30}
.....

运行main.py(注意:这里我用点传递第一个参数)

python main.py 1.2.3

main.py

import sys
from test import *

if __name__ == '__main__':
   if len(sys.argv) != 2:
       print "error message"
       sys.exit(1)
   else:
       dict_name=sys.argv[1]
       #if dict_name contains '.' , replace it
       if '.' in dict_name:
           temp_name=dict_name.replace(".","")   #gives me 123
       else:
           temp_name = dict_name

       #here i want to print the content of dict from test.py
       print config_123    #it prints dict (as i am importing * from test)
       #but i need to create it dynamically.
       print "config_"+temp_name    #obviously it prints it as a string "config_123"  
       #how should i call it here? 

在这种情况下,如何从config_123拨打test.py并显示字典?

3 个答案:

答案 0 :(得分:1)

使用import test导入模块并在模块上使用getattr()

import test

print getattr(test, 'config_123')

输出:

{'age': 25, 'name': 'Dave'}

或者在你的情况下:

print getattr(test, 'config_' + temp_name )

答案 1 :(得分:1)

我不确定这是否是最佳方式,但它似乎有用。

您可以使用内置的locals()函数将任何局部变量作为字典。然后,dict的get函数似乎得到了正确的配置:

git push <remote> <branch> --force

输出如下:

import sys, test

dname = sys.argv[1]
config1 = {'name':'Bob'}
config2 = {'name':'Alice'}

#if the variable is local
print locals().get(dname, None)
#if it's in the test module
#config = getattr(test, dname)

答案 2 :(得分:1)

您还可以将配置存储为一个键入其名称的字典,然后从那里获取。

test.py
=======

configs = {'config_123': {"name":"Dave","age":25},
           'config_89033': {"name":"alex","age":30}}


main.py
=======
from test import configs

config = configs.get('config_123')
相关问题