[英]Python3 - Convert a string to dict
我有此字符串,希望将其转换为字典:
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"'}
这来自本文档部分中的示例。 因此,如果传递一个在每次迭代中提供两个元素的Iterable,则dict
可以使用它来创建字典对象。
在这种情况下,我们首先使用data.split()
根据空格字符拆分字符串,然后根据=
拆分每个字符串,以便获得键值对。
注意:如果您确定数据在字符串中的任何地方都不会包含"
字符,则可以先替换该字符,然后再执行字典创建操作,如下所示
>>> dict(item.split('=') for item in data.replace('"', '').split())
{'width': '535', 'height': '50', 'valign': 'bottom', 'class_': 'template_title'}
我对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
如果您没有将变量定义为字符串。 您只有变量。
您可以查看以下功能,
这些将为您提供字典,您可以对其进行操作,过滤,进行各种操作。
像这样
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)
以这种方式查看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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.