I have to check if a dictionary is the same as it was yesterday, if it has changed.
In PHP I could have serialized an array and compared the resulting strings from yesterday and today. However, I don’t know how to do it in Py. I’ve read a little about Pickle and maybe it could be done with md5 somehow?
So basically I need a way to dismantle a dict into a comparable, storable value that is not a file and can be hardcoded into .py file.
Thanks,
A.R.
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!)
2) MD5 (best if you only want to check equality)
3) Pickling (serialization)
The
picklemodule 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):You can copy-and-paste this representation into your source code if you want the object serialized as a string .