Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary : removing u' chars

Tags:

python

mongodb

How do I remove u chars from the following dictionary?

{u'name': u'A', u'primary_key': 1}   

This data is coming from Mongo Database find() query

so that it looks like

{'name': 'A', 'primary_key': 1} 
like image 371
daydreamer Avatar asked Nov 12 '11 00:11

daydreamer


People also ask

How do I get rid of U in Python?

In python, to remove Unicode ” u “ character from string then, we can use the replace() method to remove the Unicode ” u ” from the string. After writing the above code (python remove Unicode ” u ” from a string), Ones you will print “ string_unicode ” then the output will appear as a “ Python is easy. ”.

What does U mean in Python?

The 'u' in front of a string means the string is a Unicode string. A Unicode is a way for a string to represent more characters than a regular ASCII string can.

How do you escape a Unicode character in Python?

Unicode Literals in Python Source Code Specific code points can be written using the \u escape sequence, which is followed by four hex digits giving the code point. The \U escape sequence is similar, but expects 8 hex digits, not 4.

How do you remove a non Unicode character in Python?

Remove Non-ASCII Characters From Text Python Here we can use the replace() method for removing the non-ASCII characters from the string. In Python the str. replace() is an inbuilt function and this method will help the user to replace old characters with a new or empty string.


1 Answers

Some databases such as Sqlite3 let you define converter and adapter functions so you can retrieve text as str rather than unicode. Unfortunately, MongoDB doesn't provide this option for any of the commonly needed types such as str, decimal or datetime:

  • http://api.mongodb.org/python/current/tutorial.html#a-note-on-unicode-strings
  • http://api.mongodb.org/python/current/faq.html#how-can-i-store-decimal-decimal-instances
  • http://api.mongodb.org/python/current/faq.html#how-can-i-save-a-datetime-date-instance

Having eliminated Mongo options, that leaves writing Python code to do the conversion after the data is retrieved. You could write a recursive function that traverses the result to convert each field.

As a quick-and-dirty alternative, here is a little hack that may be of use:

>>> import json, ast >>> r = {u'name': u'A', u'primary_key': 1} >>> ast.literal_eval(json.dumps(r)) {'name': 'A', 'primary_key': 1} 
like image 75
Raymond Hettinger Avatar answered Sep 24 '22 21:09

Raymond Hettinger