Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ConfigParser.items('') to dictionary

Tags:

python

How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:

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') 
like image 323
Szymon Lipiński Avatar asked Nov 20 '09 23:11

Szymon Lipiński


2 Answers

Have you tried

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

?

like image 122
Ian Clelland Avatar answered Sep 17 '22 23:09

Ian Clelland


How I did it in just one line.

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.

like image 32
Michele d'Amico Avatar answered Sep 19 '22 23:09

Michele d'Amico