如何编码python字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24508726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:43:00  来源:igfitidea点击:

How to encode python dictionary?

pythondictionaryencoding

提问by v1h5

I want to encode the sample stuff shown below:

我想对下面显示的示例内容进行编码:

name = "Myname"
status = "married"
sex = "Male"
color = {'eyeColor' : 'brown', 'hairColor' : 'golden', 'skinColor' : 'white'}

I am using base64 encoding scheme and used syntax as <field-name>.encode('base64','strict')where field-nameconsists of above mentioned fields- name, status and so on.

我使用 base64 编码方案并使用语法作为<field-name>.encode('base64','strict')wherefield-name由上述字段组成 - 名称、状态等。

Everything except dictionary "color" is getting encoded. I get error at color.encode('base64','strict')

除了字典“颜色”之外的所有内容都被编码。我在color.encode('base64','strict')

The error is as shown below:

错误如下图所示:

Traceback (most recent call last):
    color.encode('base64','strict') 
AttributeError: 'CaseInsensitiveDict' object has no attribute 'encode'

I think encode method is not appicable on dictionary. How shall I encode the complete dictionary at once? Is there any alternative to encodemethod which is applicable on dictionaries?

我认为编码方法不适用于字典。我该如何一次编码完整的字典?有没有其他encode方法可以替代适用于字典的方法?

采纳答案by Korem

encodeis 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 stron the dictionary first:

encode是字符串实例具有的方法,而不是字典。您不能简单地将它用于每个对象的每个实例。所以最简单的解决方案是先调用str字典:

str(color).encode('base64','strict')

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.

但是,当您想要解码字符串并取回该字典时,这就不那么直接了。Python 有一个模块可以做到这一点,它被称为pickle。Pickle 可以帮助您获得任何对象的字符串表示,然后您可以将其编码为 base64。解码回来后,您还可以解开它以取回原始实例。

b64_color = pickle.dumps(color).encode('base64', 'strict')
color = pickle.loads(b64_color.decode('base64', 'strict'))

Other alternatives to pickle + base64 might be json.

pickle + base64 的其他替代方案可能是json

回答by Down the Stream

# Something like this works on Python 2.7.12
from base64 import b64decode
color = {'eyeColor' : 'brown', 'hairColor' : 'golden', 'skinColor' : 'white'}
encoded_color = str(color).encode('base64','strict')
print(encoded_color)

decoded_color = b64decode(encoded_color)
print(decoded_color)

回答by Rajiv Sharma

This is another way to encode python dictionary in Python.

这是在 Python 中编码 Python 字典的另一种方式。

I tested in Python 36

我在 Python 36 中测试过

import base64

my_dict = {'name': 'Rajiv Sharma', 'designation': "Technology Supervisor"}
encoded_dict = str(my_dict).encode('utf-8')

base64_dict = base64.b64encode(encoded_dict)
print(base64_dict)

my_dict_again = eval(base64.b64decode(base64_dict))
print(my_dict_again)

Output:

输出:

b'eyduYW1lJzogJ1Jhaml2IFNoYXJtYScsICdkZXNpZ25hdGlvbic6ICdUZWNobm9sb2d5IFN1cGVydmlzb3InfQ=='
{'name': 'Rajiv Sharma', 'designation': 'Technology Supervisor'}

回答by Ani

simple and easy way:

简单易行的方法:

import json
converted_color = json.dumps(color)
encoded_color = converted_tuple.encode()
print(encoded_tuple)
decoded_color = encoded_color.decode()
orginal_form = json.load(decoded_color)

回答by Banu Soppan

color = {'eyeColor' : 'brown', 'hairColor' : 'golden', 'skinColor' : 'white'}
base64.urlsafe_b64encode(json.dumps(color).encode()).decode()