How to encode python dictionary?

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)

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

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

Other alternatives to pickle + base64 might be json.


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