Last active
July 8, 2016 10:17
-
-
Save thannaske/edfb4c087a991d2526f5194bb9be5dd8 to your computer and use it in GitHub Desktop.
Search a Python dictionary recursively for a specified key value pair
This file contains 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
''' | |
Search dictionary d containing other dictionaries or lists recursively for a specified key k with value v | |
dict d: Dictionary to search through | |
string k: Key to search for | |
object v: Value the key shall have | |
''' | |
def search_key_value(d, k, v): | |
if isinstance(d, dict): | |
for key, value in d.iteritems(): | |
if isinstance(value, list) or isinstance(value, dict): | |
if search_key_value(value, k, v): | |
return True | |
else: | |
pass | |
else: | |
try: | |
if key == k: | |
if value == v: | |
return True | |
else: | |
pass | |
else: | |
pass | |
except Exception: | |
pass | |
elif isinstance(d, list): | |
for value in d: | |
if search_key_value(value, k, v): | |
return True | |
else: | |
pass | |
else: | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment