Python将列表字符串转换为字典

关于数据类型之间相互转换的另一个问题是将列表的字符串转换为键和值的字典。这个特殊问题可能发生在我们需要将大量字符串数据转换为字典以在机器学习领域进行预处理的地方。让我们讨论完成此任务的某些方法。

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

字典推导可用于构建字典,split 函数可用于在列表中执行必要的拆分以获得字典的有效键值对。

示例:

>>> test_string = '[Nikhil:1, Akshat:2, Akash:3]'
>>> test_string
'[Nikhil:1, Akshat:2, Akash:3]'
>>> res = { sub.split(':')[0]:sub.split(':')[1]  for sub in test_string[1:-1].split(',')  }
>>> res
{'Nikhil': '1', ' Akshat': '2', ' Akash': '3'}
Python将列表字符串转换为字典
字典推导+split

方法2:使用eval() + replace()

也可以使用eval()和replace()的组合来执行此特定任务。在此方法中,eval 函数执行类似于字典理解、构造字典,replace 函数执行必要的替换。当必须将键和值转换为整数时使用eval函数。

>>> test_string = '[120:1, 190:2, 140:3]'
>>> test_string
'[120:1, 190:2, 140:3]'
>>> res = eval(test_string.replace( "[", "{" ).replace("]","}") )
>>> res
{120: 1, 190: 2, 140: 3}
Python将列表字符串转换为字典
eval() + replace()

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

(0)
上一篇 2022-12-16 16:25
下一篇 2022-12-16 21:43

相关推荐

发表回复

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