代码之家  ›  专栏  ›  技术社区  ›  Houy Narun

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

  •  1
  • Houy Narun  · 技术社区  · 4 年前

    我尝试在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'} . 谢谢

    1 回复  |  直到 4 年前
        1
  •  1
  •   Selcuk    4 年前

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

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