【问题标题】:Python3 - Convert a string to dictPython3 - 将字符串转换为字典
【发布时间】:2015-10-24 10:40:22
【问题描述】:

我有这个字符串,我希望将其转换为字典:

class_="template_title" height="50" valign="bottom" width="535"

基本上将其更改为:

dict(class_='template_title', height='50', valign='bottom', width='535')

没有什么比这更复杂的了,但我相信这个问题有多个步骤。如果您能解释解决方案或链接到一些文档会很好:)

【问题讨论】:

  • 您好@bob,您能否查看其他答案可能会对您有所帮助。谢谢

标签: python string python-3.x dictionary


【解决方案1】:

如果你想从那个字符串创建一个字典对象,你可以使用dict函数和一个生成器表达式,它根据空格然后=分割字符串,像这样

>>> data = 'class_="template_title" height="50" valign="bottom" width="535"'
>>> dict(item.split('=') for item in data.split())
{'width': '"535"', 'height': '"50"', 'valign': '"bottom"', 'class_': '"template_title"'}

这来自this documentation section 中的示例。因此,如果您传递一个在每次迭代中提供两个元素的可迭代对象,那么 dict 可以使用它来创建字典对象。

在这种情况下,我们首先使用data.split() 分割基于空白字符的字符串,然后基于= 分割每个字符串,这样我们将得到键值对。

注意:如果您确定数据在字符串中的任何位置都不会有" 字符,那么您可以先替换它,然后进行字典创建操作,像这样

>>> dict(item.split('=') for item in data.replace('"', '').split())
{'width': '535', 'height': '50', 'valign': 'bottom', 'class_': 'template_title'}

【讨论】:

    【解决方案2】:

    如果您没有将变量定义为字符串。你只有变量。

    您可以查看以下功能,

    • dir() 将为您提供范围内变量的列表:
    • globals() 会给你一个全局变量字典
    • locals() 会给你一个局部变量字典

    这些将为您提供可以操作、过滤和各种操作的字典。

    类似的,

    class_m="template_title" 
    height_m="50" 
    valign_m="bottom" 
    width_m="535"
    
    allVars = locals()
    myVars = {}
    for key,val in allVars.items():
        if key.endswith('_m'):
            myVars[key] = val
    
    print(myVars)
    

    【讨论】:

      【解决方案3】:

      往这边看,查看LIVE

      ori = 'class_="template_title" height="50" valign="bottom" width="535"'
      final = dict()
      for item in ori.split():
          pair = item.split('=')
          final.update({pair[0]: pair[1][1:-1]})
      print (final)
      

      输出:

      {'class_': 'template_title', 'valign': 'bottom', 'width': '535', 'height': '50'}
      

      【讨论】:

        【解决方案4】:

        我不熟悉 Python 3,所以这可能不是最优雅的解决方案,但这种方法会奏效。

        首先用空格分割字符串。 list_of_records = string.split()

        这会返回一个列表,在您的情况下看起来像这样:

        ['class_="template_title"', 'height="50"', 'valign="bottom"', 'width="535"']

        然后遍历列表并用'='分割每个元素。

        for pair in list_of_records:
            key_val = pair.split('=')
            key = pair[0]
            val = pair[1]
        

        现在在循环体中,只需将其添加到字典中即可。

        d[key] = val
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-25
          • 1970-01-01
          相关资源
          最近更新 更多