[英]Elegant way to convert string to dict and back
Is there an elegant one-liner to convert this type of string to dict?是否有一种优雅的单线将这种类型的字符串转换为 dict? I googled now for an hour, but without several loops of splitting strings I can't get it to work.
我现在用谷歌搜索了一个小时,但是没有几个分割字符串的循环,我无法让它工作。
Input = "2:9, 6:90, 7:60"
Output = {'2': 9, '6': 90, '7': 60}
I would also need the reverse operation from dict to string.我还需要从字典到字符串的反向操作。
Performance wise most efficient will be normal for
loop:性能方面最有效的将是正常
for
循环:
my_string = "2:9, 6:90, 7:60"
my_dict = {}
for s in my_string.split(', '):
k, v = s.split(":")
my_dict[k] = int(v)
where my_dict
will contain:其中
my_dict
将包含:
>>> my_dict
{'2': 9, '7': 60, '6': 90}
To get back the same string, you can perform .join()
on dict.items()
as:要取回相同的字符串,您可以在
dict.items()
) 上执行.join()
) 为:
>>> ", ".join("{}:{}".format(k, v) for k, v in my_dict.items())
'2:9, 7:60, 6:90'
Or, you can also type-cast the dict to string and do some formatting on it like:或者,您也可以将 dict 类型转换为字符串并对其进行一些格式化,例如:
>>> str(my_dict)[1:-1].replace(": ", ":").replace("'", "")
'2:9, 7:60, 6:90'
You can use ast.literal_eval
and put brackets at each end of the string although your keys will be ints not strings.您可以使用
ast.literal_eval
并将括号放在字符串的每一端,尽管您的键将是整数而不是字符串。
from ast import literal_eval
Input = "2:9, 6:90, 7:60"
Output = literal_eval(f"{{{input}}}")
{2: 9, 6: 90, 7: 60}
To fix the output to be string keys just convert them by hand要将 output 修复为字符串键,只需手动转换它们
Output = dict(zip(map(str, Output), Output.values()))
{'2': 9, '7': 60, '6': 90}
Without importing any libraries you would need to use str.split
在不导入任何库的情况下,您需要使用
str.split
Output = dict(s.split(':') for s in Input.split(', '))
{'2': '9', '6': '90', '7': '60'}
Although now your values are strings so you'd need to fix that.虽然现在你的值是字符串,所以你需要修复它。
Output = dict(zip(Output, map(int, Output.values())))
{'2': 9, '7': 60, '6': 90}
Well without asking questions, if you want a one liner that makes the key a string and the value an int:好吧,不问问题,如果你想要一个使键成为字符串而值成为 int 的单行:
dict([[j[0].strip(), int(j[1])] for j in [i.split(':') for i in Input.split(',')]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.