Python3 - 将字符串转换为dict

时间:2015-08-02 03:53:12

标签: python string python-3.x dictionary

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

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

基本上将其改为:

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

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

4 个答案:

答案 0 :(得分:11)

如果要从该字符串创建字典对象,可以使用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中的示例。因此,如果传递一个iterable,它在每次迭代时都会给出两个元素,那么dict可以使用它来创建一个字典对象。

在这种情况下,我们首先根据空格字符data.split()拆分字符串,然后根据=拆分每个字符串,这样我们就可以获得键值对。

注意:如果你确定数据在字符串中的任何地方都没有"字符,那么你可以先替换它,然后再进行字典创建操作,就像这样< / p>

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

答案 1 :(得分:0)

我不熟悉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

答案 2 :(得分:0)

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

您可以查看以下功能

  • 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 :(得分:0)

这样看,查看LIVE

ConcurrentMap<String, Long> map = new ConcurrentHashMap<String, Long>();

public long addTo(String key, long value) {
    return map.merge(key, value, Long::sum);
}

输出:

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)
相关问题