Convert String to Dict or List in Python?

后端 未结 2 567
谎友^
谎友^ 2021-01-16 19:19

convert this string to list or dictionary in python?

[\'[\', \'{\', \'u\', \"\'\", \'f\', \'i\', \'r\', \'s\', \'t\', \'_\', \'n\', \'a\', \'m\', \'e\', \"\'         


        
相关标签:
2条回答
  • 2021-01-16 19:44
    >>> 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?

    0 讨论(0)
  • 2021-01-16 19:54

    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!

    0 讨论(0)
提交回复
热议问题