Program Tip

ConfigParser.items ( '')를 사전으로 변환

programtip 2020. 12. 2. 21:48
반응형

ConfigParser.items ( '')를 사전으로 변환


ConfigParser.items ( 'section')의 결과를 사전으로 변환하여 다음과 같은 문자열 형식을 지정하려면 어떻게해야합니까?

import ConfigParser

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

connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
                     "password='%(password)s' port='%(port)s'")

print connection_string % config.items('db')

이것은 실제로 이미 config._sections. 예:

$ cat test.ini
[First Section]
var = value
key = item

[Second Section]
othervar = othervalue
otherkey = otheritem

그리고:

>>> from ConfigParser import ConfigParser
>>> config = ConfigParser()
>>> config.read('test.ini')
>>> config._sections
{'First Section': {'var': 'value', '__name__': 'First Section', 'key': 'item'}, 'Second Section': {'__name__': 'Second Section', 'otherkey': 'otheritem', 'othervar': 'othervalue'}}
>>> config._sections['First Section']
{'var': 'value', '__name__': 'First Section', 'key': 'item'}

편집 : 내가 더 내 대답을 통해 섹션을 통과하지 않고 같은 일을하는 방법을 설명합니다 때문에 같은 문제에 대한 내 솔루션을 downvoted하고 dict()있기 때문에, config._sections되어 이미 당신을위한 모듈에서 제공 .

test.ini 예 :

[db]
dbname = testdb
dbuser = test_user
host   = localhost
password = abc123
port   = 3306

마술 일어나기 :

>>> config.read('test.ini')
['test.ini']
>>> config._sections
{'db': {'dbname': 'testdb', 'host': 'localhost', 'dbuser': 'test_user', '__name__': 'db', 'password': 'abc123', 'port': '3306'}}
>>> connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'"
>>> connection_string % config._sections['db']
"dbname='testdb' user='test_user' host='localhost' password='abc123' port='3306'"

따라서이 솔루션은 잘못된 것이 아니며 실제로는 한 단계도 덜 필요합니다. 들러 주셔서 감사합니다!


시도해 보셨습니까

print connection_string % dict(config.items('db'))

?


한 줄로 어떻게했는지.

my_config_parser_dict = {s:dict(config.items(s)) for s in config.sections()}

No more than other answers but when it is not the real businesses of your method and you need it just in one place use less lines and take the power of dict comprehension could be useful.


I know this was asked a long time ago and a solution chosen, but the solution selected does not take into account defaults and variable substitution. Since it's the first hit when searching for creating dicts from parsers, thought I'd post my solution which does include default and variable substitutions by using ConfigParser.items().

from ConfigParser import SafeConfigParser
defaults = {'kone': 'oneval', 'ktwo': 'twoval'}
parser = SafeConfigParser(defaults=defaults)
parser.set('section1', 'kone', 'new-val-one')
parser.add_section('section1')
parser.set('section1', 'kone', 'new-val-one')
parser.get('section1', 'ktwo')
parser.add_section('section2')
parser.get('section2', 'kone')
parser.set('section2', 'kthree', 'threeval')
parser.items('section2')
thedict = {}
for section in parser.sections():
    thedict[section] = {}
    for key, val in parser.items(section):
        thedict[section][key] = val
thedict
{'section2': {'ktwo': 'twoval', 'kthree': 'threeval', 'kone': 'oneval'}, 'section1': {'ktwo': 'twoval', 'kone': 'new-val-one'}}

A convenience function to do this might look something like:

def as_dict(config):
    """
    Converts a ConfigParser object into a dictionary.

    The resulting dictionary has sections as keys which point to a dict of the
    sections options as key => value pairs.
    """
    the_dict = {}
    for section in config.sections():
        the_dict[section] = {}
        for key, val in config.items(section):
            the_dict[section][key] = val
    return the_dict

For an individual section, e.g. "general", you can do:

dict(parser['general'])

Combining Michele d'Amico and Kyle's answer (no dict), produces a less readable but somehow compelling:

{i: {i[0]: i[1] for i in config.items(i)} for i in config.sections()}

Here is another approach using Python 3.7 with configparser and ast.literal_eval:

game.ini

[assets]
tileset = {0:(32, 446, 48, 48), 
           1:(96, 446, 16, 48)}

game.py

import configparser
from ast import literal_eval

config = configparser.ConfigParser()
config.read('game.ini')

# convert a string to dict
tileset = literal_eval(config['assets']['tileset'])

print('tileset:', tileset)
print('type(tileset):', type(tileset))

output

tileset: {0: (32, 446, 48, 48), 1: (96, 446, 16, 48)}
type(tileset): <class 'dict'>

참고URL : https://stackoverflow.com/questions/1773793/convert-configparser-items-to-dictionary

반응형