Python 2.6如何将此字符串转换为字典?
问题描述:
str = "{ u'source_ip', u'127.0.0.1'}, { u'db_ip', u'43.53.696.23'}, { u'db_port', u'3306'}, { u'user_name', u'uz,ifls'} "
我怎么转换这个字符串字典?Python 2.6如何将此字符串转换为字典?
"source_ip":"127.0.0.1","db_ip":"43.53.696.23","db_port":"3306"
我已经试过
str = dict(str)
,但它没有工作
答
这些碎片看起来像蟒蛇套。如果通过ast.literal_eval
运行它们,你得到的东西接近,但由于集是无序的,你不能保证这两个项目是关键,这就是价值。这是一个彻头彻尾的破解,但我用parens替换了大括号,以使它们看起来更像元组,并从那里制作字典。
>>> mystr = "{ u'source_ip', u'127.0.0.1'}, { u'db_ip', u'43.53.696.23'}, { u'db_port', u'3306'}, { u'user_name', u'uz,ifls'} "
>>> mystr = mystr.replace('{', '(').replace('}', ')')
>>> import ast
>>> mydict = dict(ast.literal_eval(mystr))
>>> mydict
{u'user_name': u'uz,ifls', u'db_port': u'3306', u'source_ip': u'127.0.0.1', u'db_ip': u'43.53.696.23'}
>>>
+1
功能性和完整性 - 无论是否hacky,实用性都会胜过纯粹。 – TigerhawkT3
答
我不知道是否要将整个输入字符串转换为字典或不是,因为您给出的输出让我困惑。 否则,我的回答能给你像你想在一个字典格式第二个加亮后文本的输出:
a = "{ u'source_ip', u'127.0.0.1'}, { u'db_ip', u'43.53.696.23'}, { u'db_port', u'3306'}, { u'user_name', u'uz,ifls'} "
c = a.replace("{", '').replace("}","").replace(" u'", '').replace("'", '').replace(" ", "").split(",")
d, j = {}, 0
for i in range(len(c)):
if j +2 > len(c):
break
if c[j] == "user_name":
#d[c[j]] = "uz,ifls" #uncomment this line to have a complete dict
continue
d[c[j]] = c[j+1]
j += 2
输出:
print d
{'db_port': '3306', 'source_ip': '127.0.0.1', 'db_ip': '43.53.696.23'}
print type(d)
<type 'dict'>
如果您希望您的字符串取消第一个完整的字典这是上面评论的,并且输出将是该行:
print d
{'user_name': 'uz,ifls', 'db_port': '3306', 'source_ip': '127.0.0.1', 'db_ip': '43.53.696.23'}
print type(d)
<type 'dict'>
答
的几点:
- 顶层数据结构实际上是一个元组(因为在Python,
1, 2, 3
相同(1, 2, 3)
。 - 正如其他人所指出的那样,内部数据结构都设置文字,这是没有顺序的。
- 集文字都是用Python 2.6实现,但不在其
ast.literal_eval
功能,这是arguably a bug。 - 事实证明,你可以让自己的自定义功能
literal_eval
,使其做你想做的。
from _ast import *
from ast import *
# This is mostly copied from `ast.py` in your Python source.
def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
sets, booleans, and None.
"""
if isinstance(node_or_string, str):
node_or_string = parse(node_or_string, mode='eval')
if isinstance(node_or_string, Expression):
node_or_string = node_or_string.body
def _convert(node):
if isinstance(node, (Str)):
return node.s
elif isinstance(node, Tuple):
return tuple(map(_convert, node.elts))
elif isinstance(node, Set):
# ** This is the interesting change.. when
# we see a set literal, we return a tuple.
return tuple(map(_convert, node.elts))
elif isinstance(node, Dict):
return dict((_convert(k), _convert(v)) for k, v
in zip(node.keys, node.values))
raise ValueError('malformed node or string: ' + repr(node))
return _convert(node_or_string)
那么我们可以这样做:
>>> s = "{ u'source_ip', u'127.0.0.1'}, { u'db_ip', u'43.53.696.23'}, { u'db_port', u'3306'}, { u'user_name', u'uz,ifls'} "
>>> dict(literal_eval(s))
{u'user_name': u'uz,ifls', u'db_port': u'3306', u'source_ip': u'127.0.0.1', u'db_ip': u'43.53.696.23'}
是否有该字符串表示的正式规范?它看起来有点像修改过的Python 2.x的东西。 – tdelaney
如果是'{'source_ip':'127.0.0.1''''',那么你可以使用'eval()' – Prajwal