简体   繁体   中英

How to Print Unified Python Dictionary Within For Loop

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM