python - 如何将列表中的键值对列表转换为python中的字典
问题描述
我想读取配置文件并在字典中获取标签值对。代码需要添加空格、换行,并且只将标签值对作为字典键值。另外,需要忽略注释(以#开头)
请注意,我没有太多使用 Python 的经验,很高兴被指出实现它或改进整个代码的最佳方法。
File Example:
Parser.field_msgtypes.currency = GBP,EUR
Listener.mode = //blp/ref
Parser.field_mappings.ID_SEC = SECID
Engine.session.UATD.connection.transacted = 0
InternalMessage.formatType = STRB
InternalMessage.defaultVersionId =
这是我的代码:
class ConfigFileReader:
file_prefix = 'import';
file_suffix = 'properties';
pfd = '/user/myusername/dev/';
pf = '/user/myusername/';
def setConfigFileList(self):
genFile = [arg for arg in self.args[1:] if arg]; #ignore filename
custom_file_middle = None;
for arg in genFile:
if custom_file_middle is None:
custom_file_middle = arg;
else:
custom_file_middle = ".".join([custom_file_middle,arg]);
custom_file = ".".join([self.file_prefix,custom_file_middle,self.file_suffix]);
custom_file_path_pfd = "".join([self.pfd,custom_file]);
custom_file_path_pf = "".join([self.pf,custom_file]);
if os.path.exists(custom_file_path_pfd):
print ("Loading custom file...... %s" % custom_file_path_pfd);
self.dict_file_pfd[custom_file] = custom_file_path_pfd;
elif os.path.exists(custom_file_path_pf):
print ("Loading custom file...... %s" % custom_file_path_pf);
self.dict_file_pf[custom_file] = custom_file_path_pf;
else:
print ("File not found......[%s] [%s]" % (custom_file,arg));
def loadConfigFiles(self):
self.loadConfigKeys(self.dict_file_pfd);
self.loadConfigKeys(self.dict_file_pf);
def loadConfigKeys(self,dict_file):
for key in dict_file:
file_path = dict_file[key];
filename = key;
list_tvp = [];
with open(file_path,'r') as f:
list_tvp = [line.strip() for line in f if line.strip() and not line.startswith('#')];
self.dict_config.update(dict((each.split("=")[0].strip(),each.split("=")[1].strip()) for each in list_tvp if each.split("=")[0].strip() not in self.dict_config));
if __name__ == '__main__':
args = sys.argv;
config_reader = ConfigFileReader(args);
config_reader.setConfigFileList();
config_reader.loadConfigFiles();
for key,value in config_reader.dict_config.items():
print key,"=",value;
我想改变它,因为我觉得必须有一个高效且可读的版本。
self.dict_config.update(dict((each.split("=")[0].strip(),each.split("=")[1].strip()) for each in list_tvp if each.split("=")[0].strip() not in self.dict_config));
解决方案
我可以建议把它写成一个正常的循环:
for each in list_tvp:
key, value = [v.strip() for v in each.split("=")]
if key not in self.dict_config:
self.dict_config[key] = value
我不喜欢第二行。第三和第四可能会更好:
self.dict_config.setdefault(key, value)
推荐阅读
- reactjs - 使用 reactjs 在 UI 中显示 YAML 文件?
- r - 从数据框中的行复制与模式匹配的字符串并放入新数据框中的新列
- android - Koin 在关闭后重新注入实例
- sql - 需要通过查询验证日期跨度条件
- android - 在 InApp 计费库 [android] 的响应中检测测试购买
- python-3.x - 我的 ubuntu 服务器中的 Cron 作业无法启动
- puppet - kernel-devel 安装使用 puppet 抛出错误
- java - Whitelabel 错误页面 - 应用程序没有 /error 的显式映射
- gradle - Gradle复合构建`无法添加任务'包装器'作为具有该名称的任务已经存在。
- javascript - vue.js 元素 ui 将布尔数据绑定到选择列