python 如何把'a=b'这样的字符解析成dict类型
ringa_lee
ringa_lee 2017-04-17 11:50:43
0
5
1019

比如:
'a=b'这样的字符数据,转换成python中的dict类型,{'a':'b'}。

ringa_lee
ringa_lee

ringa_lee

reply all(5)
Peter_Zhu

If it is just a string like 'a=b', then the syntax is similar to QueryString, and you can use Python's urlparse.parse_qsl function:

import urlparse
ret = dict(urlparse.parse_qsl('a=b'))
巴扎黑

I assume you have a bunch of data and want to store them in the same dictionary (otherwise your question will be meaningless):

>>> import sys
>>> dict(l.split('=', 1) for l in sys.stdin)
Ty80

The first thing that comes to mind is exec:

# http://codepad.org/25Zwz7ys
namespace = {}
exec("a='b';c='d'", namespace)
del namespace['__builtins__']
print namespace

But it seems a bit inconsistent with the meaning of the question. The second thing that comes to mind is str.split, which is already mentioned above, so I won’t give an example.

Then I thought crazily 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 ret

if __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'}
阿神

dict(a=1) can be like this {'a': 1}

Please look downstairs, I didn't notice that 'a=b' is a string.

洪涛
# coding: utf-8
l = dict()
s = "a=b".split("=")
l[s[0]] = s[1]
print l
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template