使用Python将ini文件中的所有内容读取到有序字典中

时间:2018-08-10 06:29:54

标签: python python-3.x ini

我的配置ini文件:

[Component]
Componentnames1 = lf_object_road_mapping_Cfg,lf_preprocessing_Cfg
Componentnames2 = lf_database,lf_object
Componentnames3 = lf_object_road_mapping
Componentnames4 = fu_input_interface,fu_radar_configuration
Componentnames5 = Association,Association_Distance

这是读取上述ini文件的代码:

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)

对于上面的代码,我正在阅读具有随机顺序的键和值的字典。

执行后我可以得到的实际输出:

{'componentnames2': 'lf_database,lf_object',
 'componentnames4': 'fu_input_interface,fu_radar_configuration',
 'componentnames3': 'lf_object_road_mapping',
 'componentnames1': 'lf_object_road_mapping_Cfg,lf_preprocessing_Cfg',
 'componentnames5': 'Association,Association_Distance'}

预期输出:

{'componentnames1': 'lf_object_road_mapping_Cfg,lf_preprocessing_Cfg',
 'componentnames2': 'lf_database,lf_object', 
 'componentnames3': 'lf_object_road_mapping',
 'componentnames4': 'fu_input_interface,fu_radar_configuration',
 'componentnames5': 'Association,Association_Distance'}

1 个答案:

答案 0 :(得分:0)

您尝试使用OrderedDict吗?

from collections import OrderedDict
dictionary = OrderedDict()

for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)