Python 如何将分隔字符串转换为字典?

Python 如何将分隔字符串转换为字典?,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我尝试在python中将此字符串文字转换为dictionary对象,但没有成功: args = 'key_1=895, key_2=f.Comment' args = args.replace("'","") args = dict(args) 但我有一个错误: ValueError: dictionary update sequence element #0 has length 1; 2 is required 我知道我的args仍然是一个字符串,

我尝试在python中将此字符串文字转换为dictionary对象,但没有成功:

args = 'key_1=895, key_2=f.Comment'
args = args.replace("'","")
args = dict(args)
但我有一个错误:

ValueError: dictionary update sequence element #0 has length 1; 2 is required

我知道我的
args
仍然是一个字符串,因为我试图删除单个引号的
.replace()
无效。怎样?请帮助我转换为dictionary对象,我只需要它作为结果:
{'key_1':895,'key_2':'f.Comment'}
。谢谢

该字符串中没有单引号。单引号仅用于标记字符串文字的开头和结尾;它们不是字符串本身的一部分

要将字符串解析到字典中,可以使用
.split()
方法和生成器表达式:

>>> dict(part.strip().split("=") for part in args.split(","))
{'key_1': '895', 'key_2': 'f.Comment'}

该字符串中没有单引号。单引号仅用于标记字符串文字的开头和结尾;它们不是字符串本身的一部分。@Selcuk,啊,明白了,但正如这
args='key\u 1=895,key\u 2=f.Comment'
如何将其转换为dict?我知道正确的类型应该是dict(key_1=895,key2=“f.Comment”)。谢谢,很好,非常感谢。此外,感谢您的友好投票和编辑的问题和问题标题适合,它看起来非常棒:)都很好,我很高兴它为您工作。请注意,这会将所有值解释为字符串(例如,
“895”
),而不是预期的数字。如果需要,您需要实现额外的逻辑。我注意到,非常感谢您的帮助。