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

2024-05-14 20:01:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的配置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'}

Tags: inputobjectsectioncfgdatabaseconfigurationmappinginterface
1条回答
网友
1楼 · 发布于 2024-05-14 20:01:39

你试过使用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)

相关问题 更多 >

    热门问题