Last active
December 10, 2015 06:13
-
-
Save lanfon72/1d3444b5d7aaf57fb473 to your computer and use it in GitHub Desktop.
snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def rm_dict(dicts, keyword, recursive=True): | |
| """ remove a keyword(k-v pair) from (nest) dict. default is recursived. | |
| :param: dicts - an dict (nested allow). | |
| :param: keyword - an tuple with 2 values, means (key, value). | |
| :param: recursive - recursive search, default is True. | |
| ... admonition : doctest string below. | |
| pretty a as: | |
| a = \ | |
| { | |
| 'name':'adam', | |
| 'child':{ | |
| 'name':'adam', | |
| 'father':'adam', | |
| 'child':{ | |
| 'name':'eve', | |
| 'father':'adam', | |
| 'child':{ | |
| 'name':"adam" | |
| } | |
| } | |
| } | |
| } | |
| >>> a = {'child': {'child': {'child': {'name': 'adam'}, 'name': 'eve', 'father': \ | |
| 'adam'}, 'name': 'adam', 'father': 'adam'}, 'name': 'adam'} | |
| >>> rm_dict(a, ('name', 'eve')) | |
| 1 | |
| >>> rm_dict(a, ('father', 'eve')) | |
| 0 | |
| >>> rm_dict(a, ('father', 'adam'), recursive=False) | |
| 0 | |
| >>> rm_dict(a, ('father', 'adam'), recursive=True) | |
| 2 | |
| >>> a | |
| {'child': {'child': {'child': {'name': 'adam'}}, 'name': 'adam'}, 'name': 'adam'} | |
| >>> rm_dict(a, ('name', 'adam'), recursive=False) | |
| 1 | |
| >>> a | |
| {'child': {'child': {'child': {'name': 'adam'}}, 'name': 'adam'}} | |
| >>> rm_dict(a, ('name', 'adam')) | |
| 2 | |
| >>> a | |
| {'child': {'child': {'child': {}}}} | |
| >>> | |
| """ | |
| k, v = keyword | |
| count = 0 | |
| if k in dicts.keys(): | |
| if dicts.get(k) == v: | |
| dicts.pop(k) | |
| count += 1 | |
| # verbose output. | |
| # elif not isinstance(dicts.get(k), dict): | |
| # print("found key in {}, but value {} equal {}.".format(k, v, dicts.get(k))) | |
| if recursive: | |
| for val in dicts.values(): | |
| if isinstance(val, dict): | |
| count += rm_dict(val, keyword, recursive) | |
| return count | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod(verbose=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment