Python code for converting string type to dict type

Source: Internet
Author: User
Tags eval in python

I saved some username, password, host, port, and other things related to database connection as a string in the database. I want to use MySQLdb to check the connection information of these databases, you need to pass the username, password, host, port, and other information in the database information to MySQLdb as parameters. connect (). In this case, '{"host": "192.168.11.22 & Prime;," port ": 3306," user ":" abc "," passwd ":" 123 & Prime ;, "db": "mydb", "connect_timeout": 10} '"and other strings are converted to dict.

In python, convert string to a dict. I know the following three methods:
1. ast. literal_eval () is commonly used by me. It depends on python2.6 or above. According to the introduction, it is safer than direct eval.
2. eval () is a good method on the premise that the string content is controllable and secure.
3. json. loads () the loads method provided by json is good, but the string in key/value is converted to unicode.

View instance code: https://github.com/smilejay/python/blob/master/py2014/string2dict.py

The code is as follows: Copy code
'''
Created on Oct 14,201 4
 
@ Author: Jay <smile665@gmail.com>
'''
 
Import MySQLdb
Import ast
Import json
 
 
Def my_run ():
Try:
S = '{"host": "192.168.11.22", "port": 3306, "user": "abc ",
"Passwd": "123", "db": "mydb", "connect_timeout": 10 }'
D = ast. literal_eval (s)
Print type (d)
Print d
D1 = eval (s)
Print type (d1)
Print d1
D2 = json. loads (s)
Print type (d2)
Print d2
MySQLdb. Connect (host = d ['host'], port = d ['port'], user = d ['user'],
Passwd = d ['passwd'], db = d ['DB'],
Connect_timeout = d ['connect _ timeout'])
Print 'right'
Except t Exception, e:
Print 'wrong % s' % e
 
 
If _ name _ = '_ main __':
My_run ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.