The problem with dictionaries is their undefined order. You must make sure you always get the same result of equal dictionaries (if you want to compare them as strings).
You could do it in multiple ways:
1) Python hash (only for checking equality; hash implementation might be specific to the Python version!)
print hash(str(sorted({1 : 2, 3 : 4}.items())))
2) MD5 (best if you only want to check equality)
import hashlib
print hashlib.md5(str(sorted({1 : 2, 3 : 4}.items()))).hexdigest()
3) Pickling (serialization)
import pickle
serializedString = pickle.dumps({1 : 2, 3 : 4})
The pickle
module has different protocols (and I think it doesn't sort the dictionary items), so you can't do string comparison. You have to unpickle the data to a dictionary and then compare the old and new dictionary directly (d = pickle.loads(serializedString)
).
4) Item tuple representation (serialization)
According to your comment, you want something embeddable into Python source code. As S.Lott suggested, you can use the object representation of someDictionary.items()
, which is a list containing all (key, value) combinations as tuples (most probably unsorted):
>>> repr({1 : 2, 3 : 4}.items())
'[(1, 2), (3, 4)]'
You can copy-and-paste this representation into your source code if you want the object serialized as a string .