0

I would like to encode a list in ASCII.

My list:

data = {u'ismaster': True, u'maxWriteBatchSize': 1000, u'ok': 1.0, u'maxWireVersion': 3, u'minWireVersion': 0}

My goal:

data = {'ismaster': True, 'maxWriteBatchSize': 1000, 'ok': 1.0, 'maxWireVersion': 3, 'minWireVersion': 0}

Currently I do this:

>>>data_encode = [x.encode('ascii') for x in data]
>>>print(data_encode)
['maxWireVersion', 'ismaster', 'maxWriteBatchSize', 'ok', 'minWireVersion']

See Website to convert a list of strings

I lost some values with this method.

3
  • 1
    data is not a list but a dict Commented Mar 22, 2016 at 13:00
  • Why do you want this? Having your strings in Unicode (the u'...' prefix) is usually a good thing. Commented Mar 22, 2016 at 13:07
  • It's to do a insert in database Commented Mar 22, 2016 at 13:14

2 Answers 2

4

It's because you are converting to an actual list, but you originally had a dictionary. Just do this:

data = {key.encode("ascii"): value for key, value in data.items()}

You were using a list comprehension, but what you wanted was a dict comprehension.

Sign up to request clarification or add additional context in comments.

Comments

0

The 'u' in front of the string values means the string has been represented as unicode. It is a way to represent more characters than normal ASCII.

You will end up with problems if your dictionary contains special characters

strangeKey = u'Ознакомьтесь с документацией'

represented as u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'

 asciirep = strangeKey.encode("ascii")

will raise this error

SyntaxError: Non-ASCII character '\xd0' in ...

If you still want it, but with the risk of raising a few exceptions you can use the following

  • From Python 2.7 and 3 onwards, you can just use the dict comprehension syntax directly:

    d = {key.encode("ascii"): value for (key, value) in data.items()}

  • In Python 2.6 and earlier, you need to use the dict constructor :

    d = dict((key.encode("ascii"), value) for (key, value) in data.items())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.