的幾點:
- 頂層數據結構實際上是一個元組(因爲在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