I wonder if it is possible to achieve the following in Python:
I have a nested dictionary nested_dict
, which maps each three-element tuple (a, b, c)
to a sub-dictionary sub_dict
, and I have another list list_b
containing all the elements corresponding to the second element (i.e. the one denoted by b
) in the tuple keys above.
Given nested_dict
and list_b
, as well as a fixed pair of a
and c
(i.e. the first and the third element of a tuple key, respectively), I want to obtain a sorted iterator over the sub-dictionaries based on the elements in list_b
that forms a part of the tuple keys, in other words, by using this iterator, I can iterate through the returned sub-dictionaries like 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 ...
and each b_i
is in list_b
I am thinking along this line:
def sorted_dict_itr (nested_dict, list_b, a, c):
return (nested_dict[(a, b, c)] for b in sorted(list_b))
But would this always return an iterator over nested_dict[(a, b, c)]
by the order of b
? If so, is there any more efficient way (meaning speedier code) to achieve the same?