Message384635
I want to do something like this:
hashlib.md5(json.dumps(d, sort_keys=True))
So I can check if a dict's contents are the same as a DB version, but I can't guarantee that all the keys are strings, so it breaks, annoyingly. I would very much like the apply-default-function-then-sort approach. Until then, my work-around is this:
def deep_stringize_dict_keys(item):
"""Converts all keys to strings in a nested dictionary"""
if isinstance(item, dict):
return {str(k): deep_stringize_dict_keys(v) for k, v in item.items()}
if isinstance(item, list):
# This will check only ONE layer deep for nested dictionaries inside lists.
# If you need deeper than that, you're probably doing something stupid.
if any(isinstance(v, dict) for v in item):
return [deep_stringize_dict_keys(v) if isinstance(v, dict) else v
for v in item]
# I don't care about tuples, since they don't exist in JSON
return item
Maybe it can be of some use for others. |
|
Date |
User |
Action |
Args |
2021-01-08 04:58:36 | naught101 | set | recipients:
+ naught101, zachrahan, r.david.murray, josh.r, jedwards, tanzer@swing.co.at, Aaron Hall |
2021-01-08 04:58:36 | naught101 | set | messageid: <1610081916.79.0.929455619641.issue25457@roundup.psfhosted.org> |
2021-01-08 04:58:36 | naught101 | link | issue25457 messages |
2021-01-08 04:58:36 | naught101 | create | |
|