Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unicode characters from Dictionary data in python

After using request library , am getting below dict in response.json()

{u'xyz': {u'key1': None, u'key2': u'Value2'}}

I want to remove all unicode characters and print only key value pairs without unicode chars

I have tried below method to remove , but it shows malformed string

>>> import json, ast
>>> c = {u'xyz': {u'key1': None,u'key2': u'Value2'}}
>>> ast.literal_eval(json.dumps(c))

Getting 'ValueError: malformed string'

Any suggestion on how to do it ?

like image 237
scottlima Avatar asked Jun 28 '16 11:06

scottlima


People also ask

How do I ignore Unicode in Python?

Using encode() and decode() method to remove unicode characters in Python. You can use String's encode() with encoding as ascii and error as ignore to remove unicode characters from String and use decode() method to decode() it back.


1 Answers

This snippet will helps you to preserve the data without unicode prefix notation u :

>>> import json
>>> c = {u'xyz': {u'key1': u'Value1',u'key2': u'Value2'}}
>>> print c
{u'xyz': {u'key2': u'Value2', u'key1': u'Value1'}}
>>> d = eval(json.dumps(c))
>>> print d
{'xyz': {'key2': 'Value2', 'key1': 'Value1'}}

json.dumps() will convert the dict to string type and eval() will reverse it.

Note: key1 value has changed from None to 'value1' for testing purpose

like image 116
S.K. Venkat Avatar answered Sep 20 '22 01:09

S.K. Venkat