Skip to content

Instantly share code, notes, and snippets.

@jondkelley
Last active October 24, 2021 21:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jondkelley/96fd024dd1ec736831387be82f1efe6d to your computer and use it in GitHub Desktop.
Save jondkelley/96fd024dd1ec736831387be82f1efe6d to your computer and use it in GitHub Desktop.
Python Dictionary Stuff from Stackoverflow
#The version that modifies in-place (very much like Ned Batchelders solution):
# https://stackoverflow.com/questions/3405715/elegant-way-to-remove-fields-from-nested-dictionaries
from collections import MutableMapping
from contextlib import suppress
def delete_keys_from_dict(dictionary, keys):
for key in keys:
with suppress(KeyError):
del dictionary[key]
for value in dictionary.values():
if isinstance(value, MutableMapping):
delete_keys_from_dict(value, keys)
#And the solution that returns a new object:
from collections import MutableMapping
def delete_keys_from_dict(dictionary, keys):
keys_set = set(keys) # Just an optimization for the "if key in keys" lookup.
modified_dict = {}
for key, value in dictionary.items():
if key not in keys_set:
if isinstance(value, MutableMapping):
modified_dict[key] = delete_keys_from_dict(value, keys_set)
else:
modified_dict[key] = value # or copy.deepcopy(value) if a copy is desired for non-dicts.
return modified_dict
def get_recursively(search_dict, field):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
source: https://stackoverflow.com/questions/14962485/finding-a-key-recursively-in-a-dictionary
"""
fields_found = []
for key, value in search_dict.iteritems():
if key == field:
fields_found.append(value)
elif isinstance(value, dict):
results = get_recursively(value, field)
for result in results:
fields_found.append(result)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
more_results = get_recursively(item, field)
for another_result in more_results:
fields_found.append(another_result)
return fields_found
https://stackoverflow.com/questions/7320319/xpath-like-query-for-nested-python-dictionaries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment