0

I try to print one unified Python dictionary with the section's details from the Config.ini file but Unfortunately I get separate lists or only the final dict.

I'd love to get some help from you guys.

config_path = r"<Path>\Config.ini"

    dict = {}

    config = ConfigParser.ConfigParser()
    config.read(config_path)
    sections = config.sections()

    for section in sections:
        sql_query = config.get(section, 'SQL')
        limit = config.get(section, 'Limit')
        description = config.get(section, 'Description')
        section_name = section

        dict = {'Query': sql_query,
                'Limit': limit,
                'Description': description,
                'Section': section_name}

    print dict
James
  • 875
  • 2
  • 15
  • 24

1 Answers1

0

You override your dictionary in each loop.

Version 1: List of dicts

config = ConfigParser.ConfigParser()
config.read(config_path)
sections = config.sections()

config_sections = []
for section in sections:
    config_sections.append(
        {'Query': config.get(section, 'SQL'),
         'Limit': config.get(section, 'Limit'),
         'Description': config.get(section, 'Description'),
         'Section': section})

print config_sections

Version 2: Dict with lists

config = ConfigParser.ConfigParser()
config.read(config_path)
sections = config.sections()

config_dict = {}
for section in sections:
    for name, value in [('Query', config.get(section, 'SQL')),
                        ('Limit', config.get(section, 'Limit')),
                        ('Description', config.get(section, 'Description')),
                        ('Section', [section])]:
        config_dict.setdefault(name, []).append(value)
print config_dict
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Thanks Mike for your help :) but according to your code I'm getting this output {Query[all_sections_queries], Limit[all_sections_limit]....}. What I need is this output {[query1,limit1,description1,section1],[query2,limit2,description2,section2],[query3,limit3,description3,section3]} – James Dec 19 '15 at 09:52
  • I thought this what you want. Do you ant a list with one dictionary per section? – Mike Müller Dec 19 '15 at 09:57
  • Sorry for the misunderstanding, and that's exactly what I need. – James Dec 19 '15 at 10:02
  • You can [accept](http://stackoverflow.com/help/accepted-answer) an answer if it solves your problem. – Mike Müller Dec 19 '15 at 10:07