问题
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