问题描述
我想编码下面显示的示例内容:
I want to encode the sample stuff shown below:
name = "Myname"
status = "married"
sex = "Male"
color = {'eyeColor' : 'brown', 'hairColor' : 'golden', 'skinColor' : 'white'}
我正在使用base64编码方案,并将语法用作< field-name> .encode('base64','严格的')
其中字段名称
由上述字段组成,名称,状态等。
I am using base64 encoding scheme and used syntax as <field-name>.encode('base64','strict')
where field-name
consists of above mentioned fields- name, status and so on.
除字典color之外的所有内容都被编码。
我在 color.encode('base64','strict')中得到错误
Everything except dictionary "color" is getting encoded. I get error at color.encode('base64','strict')
错误如下所示:
Traceback (most recent call last):
color.encode('base64','strict')
AttributeError: 'CaseInsensitiveDict' object has no attribute 'encode'
我认为编码方法不适用于字典。
我将如何一次编码完整的字典?
是否有替代 encode
方法适用于字典?
I think encode method is not appicable on dictionary. How shall I encode the complete dictionary at once? Is there any alternative to encode
method which is applicable on dictionaries?
推荐答案
encode
是字符串实例具有的方法,而不是字典。您不能简单地将其与每个对象的每个实例一起使用。
所以最简单的解决方案是首先在字典上调用 str
:
encode
is a method that string instances has, not dictionaries. You can't simply use it with every instance of every object.So the simplest solution would be to call str
on the dictionary first:
str(color).encode('base64','strict')
当您想要解码字符串并将该字典恢复时,这不太直接。 Python有一个模块来做到这一点,它被称为。 Pickle可以帮助您获取任何对象的字符串表示,然后可以将其编码为base64。解码之后,您也可以取消打包以取回原始实例。
However, this is less straight forward when you'd want to decode your string and get that dictionary back. Python has a module to do that, it's called pickle. Pickle can help you get a string representation of any object, which you can then encode to base64. After you decode it back, you can also unpickle it to get back the original instance.
b64_color = pickle.dumps(color).encode('base64', 'strict')
color = pickle.loads(b64_color.decode('base64', 'strict'))
其他pickle + base64的替代方法可能是 。
Other alternatives to pickle + base64 might be json.
这篇关于如何编码python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!