python - Return a sorted iterator of dictionaries based on the keys used for obtaining these dictionaries -
i wonder if possible achieve following in python:
i have nested dictionary nested_dict, maps each three-element tuple (a, b, c) sub-dictionary sub_dict, , have list list_b containing elements corresponding second element (i.e. 1 denoted b) in tuple keys above.
given nested_dict , list_b, fixed pair of a , c (i.e. first , third element of tuple key, respectively), want obtain sorted iterator on sub-dictionaries based on elements in list_b forms part of tuple keys, in other words, using iterator, can iterate through returned sub-dictionaries this:
nested_dict[(a, b_1, c)], nested_dict[(a, b_2, c)], nested_dict[(a, b_3, c)], ...
where, b_1 < b_2 < b_3 ... , each b_i in list_b
i thinking along line:
def sorted_dict_itr (nested_dict, list_b, a, c): return (nested_dict[(a, b, c)] b in sorted(list_b)) but return iterator on nested_dict[(a, b, c)] order of b? if so, there more efficient way (meaning speedier code) achieve same?
yes, works.
keeping sorted collection in place of keeping list_b , sorting on fly improve efficiency—but of course may reduce efficiency elsewhere matters more.
there's no other way improve algorithmic complexity—dict lookups constant-time, , iterating list fast iterating possibly be.
you might able speed things small constant factor avoiding need hash each (a, b, c) tuple in various different ways, doubt make difference.
you can speed things few opcodes various micro-optimizations related variable scope , whether yield values or return generator, it's hard imagine ever matter.
Comments
Post a Comment