convert dsn string in python to kwargs

北慕城南 提交于 2020-01-16 19:23:14

问题


I have a simple string which describes a mysql connection. The string is in this form:

dsn = 'user=dbuser database=mydbase host=localhost'

this string can contain many of the things listed in the connection params listed here:

http://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html

basically, when you connect to the database you do so something like:

cnx = MySQLConnection(user='dbuser', database='mydbase', host='localhost')

I want to create the name=value arguments for the class creation from the string. So I created some code to convert from the string format to a dictionary format that I can call with the ** operator. I did it like this:

import json, re
cnx = MySQLConnection(**json.loads('{'+','.join(re.sub(r'([a-z0-9_-]*)=([a-z0-9_-]*)','"\\1":"\\2"',dsn).split())+'}'))

It works by finding name=value patterns in the string and changing them to "name":"value" string segments, it joins them with commas between each segment, bookends the new string with { } characters (which creates a json string), then does a json loads to get that into dictionary format. It seems way too complicated to me. Is there an easier way to convert from a string like this to a dictionary?


回答1:


One simple method would be to use str.split:

>>> vals = "key=val key2=val2"
>>> dict(s.split("=") for s in vals.split())
{'key2': 'val2', 'key': 'val'}


来源:https://stackoverflow.com/questions/25857551/convert-dsn-string-in-python-to-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!