简体   繁体   English

在Python中以ASCII编码列表

[英]Encode a list in ASCII in Python

I would like to encode a list in ASCII. 我想用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 . 字符串值前面的'u'表示该字符串已表示为unicode It is a way to represent more characters than normal ASCII. 这是一种比普通ASCII表示更多字符的方法。

You will end up with problems if your dictionary contains special characters 如果字典中包含特殊字符,您将最终遇到问题

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

represented as u'\О\з\н\а\к\о\м\ь\т\е\с\ь \с \д\о\к\у\м\е\н\т\а\ц\и\е\й' 表示为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: 从Python 2.7和3开始,您可以直接使用dict comprehension语法:

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

  • In Python 2.6 and earlier, you need to use the dict constructor : 在Python 2.6和更早版本中,您需要使用dict构造函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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