I have unicode u"{'code1':1,'code2':1}"
and I want it in dictionary format.
I want it in {'code1':1,'code2':1}
format.
I tried unicodedata.normalize('NFKD', my_data).encode('ascii','ignore')
but it returns string not dictionary.
Can anyone help me?
To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.
You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.
You have two options to create Unicode string in Python. Either use decode() , or create a new Unicode string with UTF-8 encoding by unicode(). The unicode() method is unicode(string[, encoding, errors]) , its arguments should be 8-bit strings.
Remarks. If encoding and/or errors are given, unicode() will decode the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is a string giving the name of an encoding; if the encoding is not known, LookupError is raised.
You can use built-in ast
package:
import ast d = ast.literal_eval("{'code1':1,'code2':1}")
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
You can use literal_eval
. You may also want to be sure you are creating a dict and not something else. Instead of assert
, use your own error handling.
from ast import literal_eval from collections import MutableMapping my_dict = literal_eval(my_str_dict) assert isinstance(my_dict, MutableMapping)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With