【问题标题】:Python 2.6 how to convert this string to dict?Python 2.6 如何将此字符串转换为字典?
【发布时间】:2017-04-16 23:17:47
【问题描述】:
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'} "

如何将此字符串转换为dict?

"source_ip":"127.0.0.1","db_ip":"43.53.696.23","db_port":"3306"

我试过了

str = dict(str)

但是没用

【问题讨论】:

  • 该字符串表示是否有正式规范?它看起来有点像修改后的 python 2.x 东西。
  • 如果是{'source_ip':'127.0.0.1}`,你可以使用eval()

标签: python string python-2.6


【解决方案1】:

我不知道您是否要将整个输入字符串转换为字典,因为您给出的输出让我感到困惑。 否则,我的回答会给你一个输出,比如你想要的 dict 格式的第二个高亮文本:

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'>

【讨论】:

    【解决方案2】:

    几点:

    • 顶层数据结构实际上是一个元组(因为在Python中,1, 2, 3和(1, 2, 3)是一样的。
    • 正如其他人指出的那样,内部数据结构是集合文字,没有顺序。
    • Set 字面量在 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'}
    

    【讨论】:

      【解决方案3】:

      这些片段看起来像 python 集。如果你通过ast.literal_eval 运行它们,你会得到一些接近的结果,但是由于集合没有排序,你不能保证这两个项目中的哪一个是键,哪一个是值。这完全是 hack,但我用括号替换了花括号,这样它们看起来更像元组,并从那里制作了字典。

      >>> 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'}
      >>> 
      

      【讨论】:

      • 功能齐全 - hacky 与否,实用性胜过纯度。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 2013-03-13
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多