python - How to clear empty keys in a dictionary with subdictionaries -
i have next regex in python:
(\"[^"]+":\s)({}|\[\]|null)(,?\s?)
i need match occurrences of "some key": [] or {} or null string, need exclude cases "some key" "note", case string is:
test= {'merda 1': {}, 'merda 2': [1,2,3], 1: """"só pra fude""", 'note': "foda-se", 'não reclama': [], 'tédio da nisso': ordereddict({'note': none, 1:2}), 'none':none, 'quero $$$': (), 'note': [], 12.2: none, 666: ordereddict(), 'fudeu': ordereddict({1:none, 2:1, 3:2}) } string_json = json.dumps(test)
the intention filter empty leafs of dictionary, need maintain ordereddicts nowadays in it.
solution: based in martin answer:
def clean_dict(dictobj): """ clean number of empty leafs of dictionary """ def del_empty_value(dictobj): """ delete empty values recursively """ key, value in dictobj.items(): if not (value or key == 'note'): del dictobj[key] elif isinstance(value, dict): del_empty_value(value) json import dumps initial_hash = len(dumps(dictobj)) while true: del_empty_value(dictobj) new_hash = len(dumps(dictobj)) if new_hash == initial_hash: break initial_hash = new_hash
why don't allow json parser hard work you?
import json s = '{"1": "\\"s\\u00f3 pra fude", "none": null, "note": [], "n\\u00e3o reclama": [], "12.2": null, "666": {}, "merda 2": [1, 2, 3], "merda 1": {}, "t\\u00e9dio da nisso": {"note": null}, "fudeu": {"1": null, "2": 1, "3": 2}, "quero $$$": []}' d = json.loads(s) result = dict((k, v) k, v in d.iteritems() if not v or k == "note")
the lastly line filters out key:value pairing bool(v)
not false
([]
, {}
, none
satisfy criteria) or key value not "note".
result:
{u'12.2': none, u'666': {}, u'none': none, u'note': [], u'n\xe3o reclama': [], u'quero $$$': [], u'merda 1': {}}
edit:
since question been updated, there's improve answer:
test= {'merda 1': {}, 'merda 2': [1,2,3], 1: """"só pra fude""", 'note': "foda-se", 'não reclama': [], 'tédio da nisso': ordereddict({'note': none, 1:2}), 'none':none, 'quero $$$': (), 'note': [], 12.2: none, 666: ordereddict(), 'fudeu': ordereddict({1:none, 2:1, 3:2}) } def delete_empty_value(test): k, v in test.items(): if not (v or type(k) ordereddict or k == 'note'): del test[k] elif isinstance(v, dict): delete_empty_value(v)
this new filter keeps key:value pair where:
the value not[]
, {}
or none
the value instance of ordereddict the key == "note" python regex string escaping substring
No comments:
Post a Comment