23

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-name consists of above mentioned fields- name, status and so on.

Everything except dictionary "color" is getting encoded. I get error at 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 encode method which is applicable on dictionaries?

Bach
  • 6,145
  • 7
  • 36
  • 61
node_analyser
  • 1,502
  • 3
  • 17
  • 34

6 Answers6

23

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.

Korem
  • 11,383
  • 7
  • 55
  • 72
  • 1
    Wonderful. Thanks @Korem. It's working like a gem. +1 as I got to know about new topic "pickle" – node_analyser Jul 01 '14 at 11:51
  • What would be a preferred way which even consumes less memory ? The first option of yours or the pickling ?? – node_analyser Jul 01 '14 at 11:57
  • @v1h5 for what purpose? I'd go with `pickle` or `cPickle` – Korem Jul 01 '14 at 12:58
  • JSON works well for situations where the round trip transformation isn't lossy. If for example you have classes like Decimal or types like sets, the conversion to JSON *is* lossy and it may be advisable to use pickle. It would depend on whether your app cares about the differences or not. – killthrush Oct 24 '18 at 01:33
  • If you get an error saying `base64` is an invalid option, see [here](https://stackoverflow.com/a/23164102/14141223) – Freddy Mcloughlan Jul 25 '22 at 04:12
4
color = {'eyeColor' : 'brown', 'hairColor' : 'golden', 'skinColor' : 'white'}
base64.urlsafe_b64encode(json.dumps(color).encode()).decode()
nucsit026
  • 652
  • 7
  • 16
Banu Soppan
  • 41
  • 1
  • 2
  • 5
    While this code snippet may solve the problem, [including an explanation](https://meta.stackoverflow.com/q/392712/2648551) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – colidyre Jan 21 '20 at 22:02
1

This is another way to encode 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'}
Rajiv Sharma
  • 6,746
  • 1
  • 52
  • 54
  • 4
    Don't ever do that! if you use this to decode urls, [here comes the remote code excecution](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – Gamification Jan 29 '19 at 20:59
1

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)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Ani
  • 11
  • 2
0
# 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)
Down the Stream
  • 639
  • 7
  • 10
0

The previous answer provided using pickle does not work with python 3.10 and gives error AttributeError: 'bytes' object has no attribute 'encode'

To encode a python dictionary and decode it

import pickle
import base64

color = {'eyeColor': 'brown', 'hairColor': 'golden', 'skinColor': 'white'}

encoded_string = base64.b64encode(pickle.dumps(color)).decode() # Base64 encoded string

dict_decoded = pickle.loads(base64.b64decode(encoded_string)) # Decoded back to dictionary
Dheer Alim
  • 21
  • 4