Search code examples
pythonlistparsingconfigparser

How can I get the values of every item in a section?


I have a configuration file with one section, and multiple items with different values. I want to put all the values (not the variables) into a list. For example:

example.ini

[main]
apple: green
orange: orange
strawberry: red
banana: yellow

example.py

config = ConfigParser.ConfigParser()
config.read('example.ini')

values = config.values('main')
for v in values:
    print v

That would print:

green
orange
red
yellow

What's the best way to do this?


Solution

  • Use the .items(section) method with a list comprehension:

    values = [v for k, v in config.items('main')]