Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unicode string dictionary into dictionary in python

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?

like image 482
Sudhir Arya Avatar asked Feb 19 '13 05:02

Sudhir Arya


People also ask

How do you turn a string of a dictionary into a dictionary?

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.

Can we convert string to dictionary in Python?

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.

How do you make a unicode string in Python?

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.

What does unicode () do in Python?

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.


2 Answers

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.

like image 90
aga Avatar answered Oct 18 '22 16:10

aga


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) 
like image 45
pyrospade Avatar answered Oct 18 '22 17:10

pyrospade