How to encode a python dictionary?

I want to code the examples shown below:

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

I use base64 encoding scheme and use syntax like <field-name>.encode('base64','strict') , where field-name consists of the above fields: name, status, etc.

Everything except the color dictionary is encoded. I get an error when color.encode('base64','strict')

The error is given below:

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

I think the encoding method is not suitable for a dictionary. How to encode a complete dictionary right away? Is there an alternative to the encode method that applies to dictionaries?

+10
source share
4 answers

encode is a method that contains string instances, not dictionaries. You cannot just use it with every instance of every object. Therefore, the simplest solution would be to first call str in the dictionary:

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

However, this is less straightforward if you want to decode your string and return this dictionary. Python has a module for this, it is called pickle . Pickle can help you get a string representation of any object that can then be encoded to base64. After decoding it, you can also print it to return the original instance.

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

Other alternatives to pickle + base64 may be json .

+15
source
 # 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) 
0
source

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) 
0
source

This is another way to encode a Python dictionary in Python.

I tested in 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'} 
-1
source

Source: https://habr.com/ru/post/971590/


All Articles