Skip to main content
 首页 » 编程设计

Python3之将字符串转换为字典

2025年05月04日21JustinYoung

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

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

基本上将其更改为:

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

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

请您参考如下方法:

如果您想从该字符串创建一个字典对象,您可以使用 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'}