New Features (nested_update, nested_delete) (#12)
* Fix for issue #10 * Renamed the test module * New Features (nested_get, nested_update, nested_delete) * Update Version to 0.3.0 * Updated Readme for new features * Removed method (nested_get) * Addressed review comments * Removed nested_get references from README * Rearanged the order of the functions
This commit is contained in:
parent
d49c15f293
commit
4564f8ed80
6 changed files with 297 additions and 58 deletions
54
nested_lookup/lookup_api.py
Normal file
54
nested_lookup/lookup_api.py
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import copy
|
||||
from six import iteritems
|
||||
|
||||
|
||||
def nested_delete(document, key):
|
||||
duplicate = copy.deepcopy(document)
|
||||
return _nested_delete(document=duplicate, key=key)
|
||||
|
||||
|
||||
def _nested_delete(document, key):
|
||||
"""
|
||||
Method to delete a key->value pair from a nested document
|
||||
Args:
|
||||
document: Might be List of Dicts (or) Dict of Lists (or)
|
||||
Dict of List of Dicts etc...
|
||||
key: Key to delete
|
||||
Return:
|
||||
Returns a document that includes everything but the given key
|
||||
"""
|
||||
if isinstance(document, list):
|
||||
for list_items in document:
|
||||
_nested_delete(document=list_items, key=key)
|
||||
elif isinstance(document, dict):
|
||||
if document.get(key):
|
||||
del document[key]
|
||||
for dict_key, dict_value in iteritems(document):
|
||||
_nested_delete(document=dict_value, key=key)
|
||||
return document
|
||||
|
||||
|
||||
def nested_update(document, key, value):
|
||||
duplicate = copy.deepcopy(document)
|
||||
return _nested_update(document=duplicate, key=key, value=value)
|
||||
|
||||
|
||||
def _nested_update(document, key, value):
|
||||
"""
|
||||
Method to update a key->value pair in a nested document
|
||||
Args:
|
||||
document: Might be List of Dicts (or) Dict of Lists (or)
|
||||
Dict of List of Dicts etc...
|
||||
key: Key to update the value
|
||||
Return:
|
||||
Returns a document that has updated key, value pair.
|
||||
"""
|
||||
if isinstance(document, list):
|
||||
for list_items in document:
|
||||
_nested_update(document=list_items, key=key, value=value)
|
||||
elif isinstance(document, dict):
|
||||
if document.get(key):
|
||||
document[key] = value
|
||||
for dict_key, dict_value in iteritems(document):
|
||||
_nested_update(document=dict_value, key=key, value=value)
|
||||
return document
|
||||
Loading…
Add table
Add a link
Reference in a new issue