dashwood.net -

Ryan Stefan's Micro Blog

Python Dict Key Recursive Attempt Function

Jun 132019

So I'm dealing with this huge database where each item has a bunch of levels and some have different keys than others. So I made a script that takes a list of lists and tries those keys, if they work the function breaks. Pretty simple and I'm sure I could make it cleaner, but it works well enough and I don't expect any 4 level items any time soon. Anyways, here's the code:

for item in items:
''' items is a list of dicts to run the keys on '''
results = {} def key_attempter(name, key_lists): nonlocal item nonlocal results for key in key_lists: if len(key) == 1: try: results[name] = item[key[0]] break except: pass elif len(key) == 2: try: results[name] = item[key[0]][key[1]] break except: pass elif len(key) == 3: try: results[name] = item[key[0]][key[1]][key[2]] break except: pass feat_lists = { 'price': [ ['hdpData', 'homeInfo', 'price'], ['price'], ['hdpData', 'priceForHDP'], ['priceLabel'], ['hdpData', 'homeInfo', 'zestimate'], ['hdpData', 'festimate'] ], 'bed': [ ['beds'], ['hdpData', 'homeInfo', 'bedrooms'] ], 'bath': [ ['baths'], ['hdpData', 'homeInfo', 'bathrooms'] ]} for k in feat_lists.keys(): key_attempter(k, feat_lists[k])

return results