import copy from copy import deepcopy def dict_get_val_path(dct,val,path=[],results=[]): '''finds the 'paths' to a value in a dictionary (the keys you need to step through to get to the value) ''' if dct == None: pass elif type(dct) == list: dummy_idx = 0 for item in dct: if item == val: temp = path[0:] temp.append(dummy_idx) results.append(temp) if isinstance(item, dict): for key in item.keys(): temp = path[0:] temp.append(dummy_idx) assign = dict_get_val_path(item,val,temp) if assign != None: if assign not in results: results.append(assign) dummy_idx+=1 elif type(dct) == dict: for key in dct.keys(): if dct[key] == val: temp = path[0:] temp.append(key) if temp not in results: results.append(temp) temp = path[0:] temp.append(key) assign = dict_get_val_path(dct[key],val,temp) if assign is not None: if assign not in results: results.append(assign) return results def processed_searches(dct,search_term): results = [] results = dict_get_val_path(dct,val=search_term,path=[],results=[]) if len(results[0]) > 0: results[0] = results[0][-1] if len(results) > 0: results = results[-1:] new_results = [] for item in results: if item not in new_results: new_results.append(item) return new_results tst_small = { "ghi": 2, "def": { "xyz": { "abc": { "Legs": [ { "yut": 6752.0, "nvm": {} } ], "wtf": { "hmm": 6751.0, "okk": 6754.0 } }, "jam": { "nfw": [ { "pft": 6757.0, "who": 6762.0 }] } } }} tst_small_2 = deepcopy(tst_small) print processed_searches(tst_small,6751.0) print processed_searches(tst_small,6752.0) print processed_searches(tst_small,6754.0) print processed_searches(tst_small,6757.0) These DON'T. Why? tst_small_3 = deepcopy(tst_small) print processed_searches(tst_small_3,6751.0) print processed_searches(tst_small_3,6752.0) print processed_searches(tst_small_3,6754.0) print processed_searches(tst_small_3,6757.0)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question