首页 > 解决方案 > 如何将列表中的键值对列表转换为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));

标签: pythonlistdictionary

解决方案


我可以建议把它写成一个正常的循环:

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)

推荐阅读