简体   繁体   中英

Convert String to Dict or List in Python?

将此字符串转换为python中的列表或字典?

['[', '{', 'u', "'", 'f', 'i', 'r', 's', 't', '_', 'n', 'a', 'm', 'e', "'", ':', ' ', 'u', "'", 'j', 'o', 'h', 'n', "'", ',', ' ', 'u', "'", 'l', 'a', 's', 't', '_', 'n', 'a', 'm', 'e', "'", ':', ' ', 'u', "'", 's', 'm', 'i', 't', 'h', "'", ',', ' ', 'u', "'", 'a', 'g', 'e', "'", ':', ' ', '2', '0', ',', ' ', 'u', "'", 'm', 'o', 'b', 'n', 'u', 'm', "'", ':', ' ', 'u', "'", '1', '2', '3', '4', '1', '9', '0', '8', "'", ',', ' ', 'u', "'", '_', 'i', 'd', "'", ':', ' ', '1', ',', ' ', 'u', "'", 'e', 'm', 'a', 'i', 'l', "'", ':', ' ', 'u', "'", 's', 'm', 'i', 't', 'h', '@', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm', "'", '}', ']']
>>> a = ['[', '{', 'u', "'", 'f', 'i', 'r', 's', 't', '_', 'n', 'a', 'm', 'e', "'", ':', ' ', 'u', "'", 'j', 'o', 'h', 'n', "'", ',', ' ', 'u', "'", 'l', 'a', 's', 't', '_', 'n', 'a', 'm', 'e', "'", ':', ' ', 'u', "'", 's', 'm', 'i', 't', 'h', "'", ',', ' ', 'u', "'", 'a', 'g', 'e', "'", ':', ' ', '2', '0', ',', ' ', 'u', "'", 'm', 'o', 'b', 'n', 'u', 'm', "'", ':', ' ', 'u', "'", '1', '2', '3', '4', '1', '9', '0', '8', "'", ',', ' ', 'u', "'", '_', 'i', 'd', "'", ':', ' ', '1', ',', ' ', 'u', "'", 'e', 'm', 'a', 'i', 'l', "'", ':', ' ', 'u', "'", 's', 'm', 'i', 't', 'h', '@', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm', "'", '}', ']']

>>> ''.join(a)
     "[{u'first_name': u'john', u'last_name': u'smith', u'age': 20, u'mobnum': u'12341908', u'_id': 1, u'email': u'smith@gmail.com'}]"

>>> import ast
>>> ast.literal_eval(''.join(a))
 [{u'_id': 1,
  u'age': 20,
  u'email': u'smith@gmail.com',
  u'first_name': u'john',
  u'last_name': u'smith',
  u'mobnum': u'12341908'}]

How did you manage to get that?

It is itself a list and you are saying to convert it to list! Try print type(a) by assigning given code as a !! Then you will get

<type 'list'>

as output!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM