Search code examples
pythoniniconfigparser

Retrieve multiple configuration keys from ini file based on dynamic list


I'm not able to pass the values of a list to a for loop which will return the value assigned to it in config file at runtime.

My config file is demo.ini:

[DEMFILE]
Name='XYZABC'
Surname='TYUIO'
Code='123'
City='Kolkata'

I have a list in which I have parameters like below:

from configparser import ConfigParser
mylist=['Name','Code']
mylist_count=len(mylist)
   
dmfg=config_object["DEMFILE"]


for i in range(mylist_count):
    getValue=dmfg[i] # ---> Throws error 
    print(f'The value of {i} is : {getValue}')   

Expected Output for getValue is as shown below:

The value of Name is : XYZABC
The value of City is : Kolkata

I want whatever the values in list that should check in config file and return the output assigned to it.

For example: Name --> XYZABC (coming from config file).


Solution

  • You can create an instance of the ConfigParser, read the .ini file and use the key rather than its index to retrieve the value:

    Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
    >>> from configparser import ConfigParser
    >>> config = ConfigParser()
    >>> config.read("demo.ini")
    ['demo.ini']
    >>> keys = ["Name", "Code"]
    >>> vals = [config["DEMFILE"][x] for x in keys]
    >>> vals
    ["'XYZABC'", "'123'"]
    

    If the quotes seem odd, config values typically aren't quoted. Either remove the quotes from the config or strip them with [x[1:-1] for x in vals].