Skip to content

Instantly share code, notes, and snippets.

@mustafakirimli
Created July 10, 2014 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustafakirimli/aa7c4febdf5ad4a847fa to your computer and use it in GitHub Desktop.
Save mustafakirimli/aa7c4febdf5ad4a847fa to your computer and use it in GitHub Desktop.
def replace_dict(obj, cbv, key=lambda x: True, value=lambda x: True):
"""
Replaces dict values recursively.
>>> cats = {
"name": "Telefon",
"desc": "Telefon modelleri",
"id": 1,
"is_active": "True",
"155": "Polis İmdat",
"child":{
"name": "Telefon - Akıllı Telefon",
"desc": "Akıllı telefon modelleri",
"id": 2,
"is_active": "True",
"112": "Hızır Acil",
"child": {
"name": "Telefon - Akıllı Telefon - Android",
"desc": "Android akıllı telefon modelleri",
"id": 3,
"is_active": "False",
"110": "İtfaiye",
}
}
}
# replace all key's value with empty string
>>> replace_dict(cats, '')
{'155': '', 'child': '', 'desc': '', 'id': '', 'is_active': '', 'name': ''}
# replace all key's value with empty string if value is not dict
>>> replace_dict(cats, '', value=lambda x: not isinstance(x, dict))
{'155': '', 'name': '', 'is_active': '', 'child': {'name': '', '112': '', 'is_active': '', 'child': {'id': '', ...
# replace all key's value with empty string if key stars with integer
>>> import re
>>> replace_dict(cats, '', key=lambda x: re.search('^\d', x))
{'155': '', 'name': u'Telefon', 'is_active': 'True', 'child': {'name': u'Telefon - Akıllı Telefon', '112': '', ...
# convert values string to boolean if the key stars with 'is_' keyword and value contains 'True' or 'False'
>>> import re
>>> replace_dict(cats,
lambda x: True if x == 'True' else False,
key=lambda x: re.search('^is_', x),
value=lambda x: re.search('^(False|True)$', x)
)
{'155': 'Polis İmdat', 'name': 'Telefon', 'is_active': True, 'child': {'name': 'Telefon - Akıllı Telefon', '112': ...
# remove parent category's name from category name which are separated by dash symbol
>>> import re
>>> replace_dict(cats,
lambda x: x.split(' - ', 1)[1:][0],
key= lambda x: re.search('name', x),
value= lambda x: re.search('-', x))
{'155': 'Polis İmdat', 'name': 'Telefon', 'is_active': 'True', 'child': {'name': 'Akıllı Telefon', '112': 'Hızır Acil', ...
"""
for k, v in obj.items():
if key(k) and value(v):
obj[k] = cbv(v) if hasattr(cbv, '__call__') else cbv
if isinstance(v, dict):
replace_dict(v, cbv, key=key, value=value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment