python能把带等号的字符串转换成字典类型吗,python等号,比如:a=b这样的字符数
python能把带等号的字符串转换成字典类型吗,python等号,比如:a=b这样的字符数
比如:
'a=b'这样的字符数据,转换成python中的dict类型,{'a':'b'}。
我假设你有一堆这种数据,要存储到同一个字典里(否则你的问题就没什么意义了):
>>> import sys>>> dict(l.split('=', 1) for l in sys.stdin)
第一想到的是 exec:
# http://codepad.org/25Zwz7ysnamespace = {}exec("a='b';c='d'", namespace)del namespace['__builtins__']print namespace
但是好像有点不合题意,第二想到的是 str.split,上面已经有了,不作举例。
然后我丧心病狂地想到 ConfigParser...
class toDict(object): def __new__(self, *data): if not data: return {} import os import ConfigParser parser = ConfigParser.ConfigParser() buf = 'buffer.buf' f = open(buf, 'w') f.write("[section_data]" + os.linesep) for i in data: f.write(i + os.linesep) f.close() parser.read(buf) items = parser.items("section_data") ret = {} for i in items: ret[i[0]] = i[1] os.remove(buf) del parser return retif __name__ == '__main__': print toDict() # {} print toDict("a=b") # {'a': 'b'} print toDict("a=b", "c=d", "你好=世界", "1=2") # {'a': 'b', '1': '2', 'c': 'd', '\xc4\xe3\xba\xc3': '\xca\xc0\xbd\xe7'}
如果只是'a=b'这样的字符串,那么跟QueryString的语法类似,用Python的urlparse.parse_qsl函数就可以搞定:
import urlparseret = dict(urlparse.parse_qsl('a=b'))
# coding: utf-8l = dict()s = "a=b".split("=")l[s[0]] = s[1]print l
dict(a=1) 是可以成这样的 {'a': 1}
请看楼下的,没注意到'a=b'是一个字符串。
编橙之家文章,
相关内容
- python jinja2模板语言获取javascript function(_index) 传过来的
- Python web开发给controller、action附加属性如何操作,pyth
- 请问Python语言中is与双等号==有什么区别及作用,pytho
- Python终端中能输出带颜色的字符吗?,python终端,今天看
- Python语言method_descriptor语法正确解释是?,,type(str.cen
- Python字符串转数字有没有更好的方法,python字符串,py
- python Burpsuite,Wireshark,Fiddler 抓包的适用场景,以及优
- Python Django生成admin页中禁止模块部分功能如何实现,
- python sort()中cmp参数有什么要求,pythoncmp,最近在看<
- 需要提交JS表单,用python脚本能完成这项工作吗,jspyth
评论关闭