[英]Convert String representation of a List to a Dictionary Python
How can I convert a str representation of the list
, such as the below string into a dictionary
?如何将
list
的 str 表示(例如以下字符串)转换为dictionary
?
a = '[100:0.345,123:0.34,145:0.86]'
Expected output :预期输出:
{100:0.345,123:0.34,145:0.86}
First tried to convert the string into a list using ast.literal_eval
.首先尝试使用
ast.literal_eval
将字符串转换为列表。 But it's showing an error as : invalid syntax
但它显示的错误为:
invalid syntax
It's showing as invalid syntax because it has the wrong brackets, so you could do它显示为无效语法,因为它有错误的括号,所以你可以这样做
ast.literal_eval(a.replace("[","{").replace("]", "}"))
Or alternatively parse the string yourself in a dictionary comprehension或者在字典理解中自己解析字符串
{x.split(":")[0]: x.split(":")[1] for x in a[1:-1].split(",")}
and if as mentioned there are [
or ]
elsewhere in your string the following may be more robust并且如果如上所述有
[
或]
在您的字符串中的其他地方,则以下内容可能更强大
ast.literal_eval("{" + a[1:-1] +"}")
我会简单地尝试
eval(a.replace('[', '{').replace(']', '}'))
To convert to a dict:转换为字典:
data = '[100:0.345,123:0.34,145:0.86]'
new_data = dict(y.split(':') for y in (x.strip().strip('[').strip(']')
for x in data.split(',')))
print(new_data)
Or if you need numbers not strings:或者,如果您需要数字而不是字符串:
new_data = dict((map(float, y.split(':'))) for y in (
x.strip().strip('[').strip(']') for x in data.split(',')))
{'100': '0.345', '123': '0.34', '145': '0.86'}
{145.0: 0.86, 123.0: 0.34, 100.0: 0.345}
Translate brackets to braces, literal_eval
.将括号翻译
literal_eval
括号, literal_eval
。
rebracket = {91: 123, 93: 125}
a = '[100:0.345,123:0.34,145:0.86]'
literal_eval(a.translate(rebracket))
Given a string representation of a dict:给定一个 dict 的字符串表示:
a = '[100:0.345,123:0.34,145:0.86]'
Ignore the containing braces [..]
, and break up the elements on commas:忽略包含的大括号
[..]
,并用逗号分隔元素:
a = a[1:-1].split(",")
For each element, separate the key and value:对于每个元素,将键和值分开:
d1 = [x.split(":") for x in a]
Reconstitute the parsed data as a dict:将解析后的数据重组为字典:
d2 = { int(k[0]) : float(k[1]) for k in d1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.