【问题标题】:Read all the contents in ini file into ordered dictionary with Python使用 Python 将 ini 文件中的所有内容读入有序字典
【发布时间】:2018-08-10 06:29:54
【问题描述】:

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

【问题讨论】:

  • 你好像对collections.OrderedDictionary很熟悉,你试过用吗?
  • 是的,我尝试过使用它,但我可以得到相同的答案。
  • 能否请您展示您对OrderedDict 的尝试仍然失败?

标签: python python-3.x ini


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2011-10-28
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多