Python dictionary : removing u' chars
up vote
36
down vote
favorite
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}
python mongodb
add a comment |
up vote
36
down vote
favorite
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}
python mongodb
5
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
1
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
2
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13
add a comment |
up vote
36
down vote
favorite
up vote
36
down vote
favorite
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}
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}
python mongodb
python mongodb
asked Nov 12 '11 at 0:56
daydreamer
30.4k125337563
30.4k125337563
5
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
1
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
2
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13
add a comment |
5
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
1
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
2
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13
5
5
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
1
1
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
2
2
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13
add a comment |
6 Answers
6
active
oldest
votes
up vote
44
down vote
accepted
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}
add a comment |
up vote
17
down vote
The u
characters that you are seeing simply mean that they are unicode strings.
If you do not want them to be unicode, you can encode them as something else, such as ASCII.
>>> s = u'hi!'
>>> s
u'hi'
>>> s2 = s.encode('ascii')
>>> s2
'hi'
add a comment |
up vote
3
down vote
You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw — you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:
cursor.execute('INSERT INTO person (name, town) VALUES (%s %s)', (name, town))
Because psycopg2 knows SQL syntax very, very well, it will leave off the u
characters as it gets your name
and town
strings and quotes and escapes them in exactly the way that this SQL statement needs.
add a comment |
up vote
3
down vote
If you simply want to convert the dict to json data string you can do:
>>> from bson.json_util import dumps
>>> data = {u'name': u'A', u'primary_key': 1}
>>> dumps(data)
'{"name": "A", "primary_key": 1}'
add a comment |
up vote
2
down vote
As sven mentions in his comment, the u
is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).
This fact should be totally transparent to you, in fact you can use str
and unicode
values interchangeably in the dicts.
>>> 'foo' in {u'foo': 5}
True
>>> {u'foo': 5}['foo']
5
>>>
add a comment |
up vote
0
down vote
You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.
One solution is to use the encode function:
old_strings = {u'name':u'A', u'primary_key':1}
newstrings = {}
for k in old_strings.keys():
newtsrings[k] = old_strings[k].encode('ascii','ignore')
This would just ignore non ascii characters.
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
44
down vote
accepted
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}
add a comment |
up vote
44
down vote
accepted
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}
add a comment |
up vote
44
down vote
accepted
up vote
44
down vote
accepted
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}
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}
edited Nov 12 '11 at 4:41
answered Nov 12 '11 at 2:43
Raymond Hettinger
130k38253348
130k38253348
add a comment |
add a comment |
up vote
17
down vote
The u
characters that you are seeing simply mean that they are unicode strings.
If you do not want them to be unicode, you can encode them as something else, such as ASCII.
>>> s = u'hi!'
>>> s
u'hi'
>>> s2 = s.encode('ascii')
>>> s2
'hi'
add a comment |
up vote
17
down vote
The u
characters that you are seeing simply mean that they are unicode strings.
If you do not want them to be unicode, you can encode them as something else, such as ASCII.
>>> s = u'hi!'
>>> s
u'hi'
>>> s2 = s.encode('ascii')
>>> s2
'hi'
add a comment |
up vote
17
down vote
up vote
17
down vote
The u
characters that you are seeing simply mean that they are unicode strings.
If you do not want them to be unicode, you can encode them as something else, such as ASCII.
>>> s = u'hi!'
>>> s
u'hi'
>>> s2 = s.encode('ascii')
>>> s2
'hi'
The u
characters that you are seeing simply mean that they are unicode strings.
If you do not want them to be unicode, you can encode them as something else, such as ASCII.
>>> s = u'hi!'
>>> s
u'hi'
>>> s2 = s.encode('ascii')
>>> s2
'hi'
answered Nov 12 '11 at 1:00
David Alber
12.7k45060
12.7k45060
add a comment |
add a comment |
up vote
3
down vote
You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw — you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:
cursor.execute('INSERT INTO person (name, town) VALUES (%s %s)', (name, town))
Because psycopg2 knows SQL syntax very, very well, it will leave off the u
characters as it gets your name
and town
strings and quotes and escapes them in exactly the way that this SQL statement needs.
add a comment |
up vote
3
down vote
You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw — you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:
cursor.execute('INSERT INTO person (name, town) VALUES (%s %s)', (name, town))
Because psycopg2 knows SQL syntax very, very well, it will leave off the u
characters as it gets your name
and town
strings and quotes and escapes them in exactly the way that this SQL statement needs.
add a comment |
up vote
3
down vote
up vote
3
down vote
You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw — you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:
cursor.execute('INSERT INTO person (name, town) VALUES (%s %s)', (name, town))
Because psycopg2 knows SQL syntax very, very well, it will leave off the u
characters as it gets your name
and town
strings and quotes and escapes them in exactly the way that this SQL statement needs.
You need to let psycopg2 encode your strings, not try to insert Python-syntax strings into your queries raw — you are putting yourself in danger of a SQL injection problem if some of the strings contain characters that SQL will interpret as ending the string. You should pass parameters to psycopg2 like this:
cursor.execute('INSERT INTO person (name, town) VALUES (%s %s)', (name, town))
Because psycopg2 knows SQL syntax very, very well, it will leave off the u
characters as it gets your name
and town
strings and quotes and escapes them in exactly the way that this SQL statement needs.
answered Nov 12 '11 at 1:29
Brandon Rhodes
51.1k1290128
51.1k1290128
add a comment |
add a comment |
up vote
3
down vote
If you simply want to convert the dict to json data string you can do:
>>> from bson.json_util import dumps
>>> data = {u'name': u'A', u'primary_key': 1}
>>> dumps(data)
'{"name": "A", "primary_key": 1}'
add a comment |
up vote
3
down vote
If you simply want to convert the dict to json data string you can do:
>>> from bson.json_util import dumps
>>> data = {u'name': u'A', u'primary_key': 1}
>>> dumps(data)
'{"name": "A", "primary_key": 1}'
add a comment |
up vote
3
down vote
up vote
3
down vote
If you simply want to convert the dict to json data string you can do:
>>> from bson.json_util import dumps
>>> data = {u'name': u'A', u'primary_key': 1}
>>> dumps(data)
'{"name": "A", "primary_key": 1}'
If you simply want to convert the dict to json data string you can do:
>>> from bson.json_util import dumps
>>> data = {u'name': u'A', u'primary_key': 1}
>>> dumps(data)
'{"name": "A", "primary_key": 1}'
answered Dec 22 '16 at 9:16
Gopal Gautam
493
493
add a comment |
add a comment |
up vote
2
down vote
As sven mentions in his comment, the u
is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).
This fact should be totally transparent to you, in fact you can use str
and unicode
values interchangeably in the dicts.
>>> 'foo' in {u'foo': 5}
True
>>> {u'foo': 5}['foo']
5
>>>
add a comment |
up vote
2
down vote
As sven mentions in his comment, the u
is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).
This fact should be totally transparent to you, in fact you can use str
and unicode
values interchangeably in the dicts.
>>> 'foo' in {u'foo': 5}
True
>>> {u'foo': 5}['foo']
5
>>>
add a comment |
up vote
2
down vote
up vote
2
down vote
As sven mentions in his comment, the u
is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).
This fact should be totally transparent to you, in fact you can use str
and unicode
values interchangeably in the dicts.
>>> 'foo' in {u'foo': 5}
True
>>> {u'foo': 5}['foo']
5
>>>
As sven mentions in his comment, the u
is an indication of the types represented in mongodb (actually it's because json is defined to use unicode).
This fact should be totally transparent to you, in fact you can use str
and unicode
values interchangeably in the dicts.
>>> 'foo' in {u'foo': 5}
True
>>> {u'foo': 5}['foo']
5
>>>
answered Nov 12 '11 at 1:02
SingleNegationElimination
110k17210257
110k17210257
add a comment |
add a comment |
up vote
0
down vote
You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.
One solution is to use the encode function:
old_strings = {u'name':u'A', u'primary_key':1}
newstrings = {}
for k in old_strings.keys():
newtsrings[k] = old_strings[k].encode('ascii','ignore')
This would just ignore non ascii characters.
add a comment |
up vote
0
down vote
You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.
One solution is to use the encode function:
old_strings = {u'name':u'A', u'primary_key':1}
newstrings = {}
for k in old_strings.keys():
newtsrings[k] = old_strings[k].encode('ascii','ignore')
This would just ignore non ascii characters.
add a comment |
up vote
0
down vote
up vote
0
down vote
You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.
One solution is to use the encode function:
old_strings = {u'name':u'A', u'primary_key':1}
newstrings = {}
for k in old_strings.keys():
newtsrings[k] = old_strings[k].encode('ascii','ignore')
This would just ignore non ascii characters.
You cannot simply remove the u from the strings, as it symbolizes, that the strings are in Unicode.
One solution is to use the encode function:
old_strings = {u'name':u'A', u'primary_key':1}
newstrings = {}
for k in old_strings.keys():
newtsrings[k] = old_strings[k].encode('ascii','ignore')
This would just ignore non ascii characters.
edited Nov 13 '11 at 6:10
answered Nov 12 '11 at 1:03
Stellarator
31418
31418
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8101649%2fpython-dictionary-removing-u-chars%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
5
The characters indicate that the strings are unicode strings. Do you have any reason for wanting to "remove" them?
– Sven Marnach
Nov 12 '11 at 0:58
when I use psycopg2 to execute statement it fails, I am assuming this is the reason ProgrammingError: 'syntax error at or near """"INSERT INTO p_dimension (id, name) VALUES (1, E'Acro Energy')""""nLINE 1: """INSERT INTO p_dimension (id, name) VALUES (1, E'Acr...n ^n'
– daydreamer
Nov 12 '11 at 0:59
1
@daydreamer You should probably post the actual code that is failing.
– Amber
Nov 12 '11 at 1:01
2
This sounds an awful lot like a problem with psycopg2 and not mongodb, considering that's where your error is. Post a full example with the problem you are really trying to solve
– SingleNegationElimination
Nov 12 '11 at 1:03
added - stackoverflow.com/questions/8101744/…
– daydreamer
Nov 12 '11 at 1:13