python str转dict。ValueError: dictionary update sequence element #0 has length 1; 2 is required

python中,将字符串中包含的字典直接使用dict()转换,会报
ValueError: dictionary update sequence element #0 has length 1; 2 is required
错误,如下:

>>> a = "{'a': 1, 'b': 2}"
>>> c = dict(a)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: dictionary update sequence element #0 has length 1; 2 is required

在python中不能只能进行转换,需要使用eval()
如下:

>>> a = "{'a': 1, 'b': 2}"
>>> c = eval(a)
>>> c
{'a': 1, 'b': 2}

你可能感兴趣的:(Python)