ConfigParser Help

Jeff Epler jepler at unpythonic.net
Mon Oct 14 14:55:13 EDT 2002


On Mon, Oct 14, 2002 at 09:38:39PM +0300, Karthikesh Raju wrote:
> well, i can live with this but would really be happy with variables a
> dictionary of the sections and its subsections as keys with the RHS
> the values for the keys.

Try something like this:

def convertConfigDict(d, sep="."):
    r = {}
    for k in d:
        s = r
        parts = k.split(sep)
        for part in parts[:-1]:
            s = s.setdefault(part, {})
        s[parts[-1]] = d[k]
    return r

>>> print convertConfigDict({'a.noofusers':'10','a.noofsources':'20','b.noofusers':'10','b.noofsources':'20'})
{'a': {'noofsources': '20', 'noofusers': '10'}, 'b': {'noofusers': '10', 'noofsources': '20'}}

I don't know if you can do this in CongfigParser, but if you have {'a':
1, 'a.b': 2}, you won't care for the results that convertConfigDict
gives you.  (You'll either get a traceback when it tries to execute
1['b']=2, or you'll lose the a.b key when r['a']=1 is executed.

Jeff




More information about the Python-list mailing list