【问题标题】:Approaching a dictionary using parameters in Python在 Python 中使用参数接近字典
【发布时间】:2016-01-25 14:25:03
【问题描述】:

我正在编写一个通用 Python 脚本,它知道如何处理 4 个不同的 SQL 表 - 根据发送的参数(表名)。 每个表名都有不同的常量——例如文件路径、文件名、查询等。 我尝试编写一个 config.py 文件,其中包含每个表的字典,然后我可以通过接近正确的字典来获得正确的常量。

例子:

Table1 = dict(
    DBName='db1',
    FolderPath='C:\\MySQL\\Table1',
    LogPath='C:\\MySQL\\Table1\\LogFile.txt' 
)
Table2 = dict(
    DBName='db2',
    FolderPath='C:\\MySQL\\Table2',
    LogPath='C:\\MySQL\\Table2\\LogFile.txt' 
)

我想查字典的方法是:

import config

name = sys.argv[1]
DBname = config.name['DBName']

唯一的问题是 - 我不能在那里写“名称”变量,我必须写准确的字典名称...

所以 - 有什么方法可以使用变量获取字典吗? 如果没有 - 有没有更好的方法来创建我需要的东西(根据发送到脚本的参数获取常量)? 非常感谢!

【问题讨论】:

  • 写一个字典的字典怎么样?喜欢config = dict( Table1 = dict( [...] ))?然后,您从用户那里获得的字符串可用于检索配置字典。

标签: python python-2.7 dictionary config


【解决方案1】:
config = {
         "name":{
                  'DBName':'blah'
                }
         }

【讨论】:

  • 正是我需要的,而且很简单...谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多