字典(dict)转为字符串(string)

我们可以比较容易的将字典(dict)类型转为字符串(string)类型。

通过遍历dict中的所有元素就可以实现字典到字符串的转换:

for key, value in sample_dic.items():
    print "\"%s\":\"%s\"" % (key, value)

字符串(string)转为字典(dict)

如何将一个字符串(string)转为字典(dict)呢?

其实也很简单,只要用 eval()或exec() 函数就可以实现了。

>>> a = "{'a': 'hi', 'b': 'there'}"
>>> b = eval(a)
>>> b
{'a': 'hi', 'b': 'there'}
>>> exec ("c=" + a)
>>> c
{'a': 'hi', 'b': 'there'}
>>>

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-01-11
猜你喜欢
  • 2022-12-23
  • 2022-01-06
  • 2021-08-06
  • 2021-11-04
  • 2022-12-23
  • 2022-01-10
  • 2019-11-06
相关资源
相似解决方案