parker
parker

Reputation: 97

Read all the content from .config file & insert into a dictionary with python

I there any way to insert all the content of config file & insert into a dictionary.

Config file is a nest dictionary:

[A]
x:1
y:2
z:3
[B]
a:4
b:5
c:6

Is there any way to to get the details as {A:{x:1,y:2,z:3}, B:{a:4,b:5,c:6}}.

Above is a sample .Can we do this with generic(not specific to this config file)

Upvotes: 1

Views: 162

Answers (1)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

Use ConfigParser:

>>> s = """
[A]
x:1
y:2
z:3
[B]
a:4
b:5
c:6"""

>>> from ConfigParser import ConfigParser
>>> from StringIO import StringIO

>>> parser = ConfigParser()
>>> parser.readfp(StringIO(s))
>>> {section: {key: value
               for key, value in parser.items(section)}
     for section in parser.sections()}
{'A': {'x': '1', 'y': '2', 'z': '3'}, 'B': {'a': '4', 'b': '5', 'c': '6'}}

Upvotes: 4

Related Questions