简体   繁体   中英

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.

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.

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'\О\з\н\а\к\о\м\ь\т\е\с\ь \с \д\о\к\у\м\е\н\т\а\ц\и\е\й'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM