Python将字符串内容转换为字典

有时,我们可能不得不将字符串内容转换为字典。该字符串可能具有特定的格式,可以进行键值转换。这种类型的问题在机器学习领域很常见。让我们讨论解决这个问题的某些方法。

以下程序代码均在Win7+Python3.8环境下测试。 

方法1:split()+字典推导式

该组合方法可用于执行此特定任务。分为两步,在第一步中,使用 split 将字符串转换为列表,然后使用字典推导式将其转换回字典。

>>> test_str = "Cfg = 1,Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1,Good = 2, CS = 3, Portal = 4'
>>> res = {key:int(val)  for key, val in  (item.split('=') for item in test_str.split(','))  }
>>> res
{'Cfg ': 1, 'Good ': 2, ' CS ': 3, ' Portal ': 4}
Python Split() 和 字典推导式
split() + 字典推导式

方法2:eval()

这个特殊问题可以使用内置函数 eval 解决,该函数在内部评估字符串并根据条件将字符串转换为字典。

>>> test_str = "Cfg = 1, Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1, Good = 2, CS = 3, Portal = 4'
>>> res = eval('dict(%s)'%test_str)
>>> res
{'Cfg': 1, 'Good': 2, 'CS': 3, 'Portal': 4}
Python eval函数
eval()

方法3:使用split()+index()+切片

>>> test_str = "Cfg = 1, Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1, Good = 2, CS = 3, Portal = 4'
>>> res = dict()
>>> x = test_str.split(',')
>>> for i in x:
...     a = i[:i.index("=")]
...     b = i[i.index("=") + 1:]
...     res[a] = b
...
>>> res
{'Cfg ': ' 1', ' Good ': ' 2', ' CS ': ' 3', ' Portal ': ' 4'}
Python split()和index()和切片
split() + index() + 切片

本文根据python-converting-string-content-to-dictionary翻译而来,不代表烟海拾贝立场,如若转载,请注明出处:https://somirror.com/3339.html

(0)
上一篇 2022-12-17 15:34
下一篇 2022-12-19 17:00

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注