user6066403
user6066403

Reputation: 213

Encode a list in ASCII in Python

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.

Upvotes: 0

Views: 365

Answers (2)

Radu Ionescu
Radu Ionescu

Reputation: 3532

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())

Upvotes: 0

zondo
zondo

Reputation: 20336

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.

Upvotes: 4

Related Questions