MLister
MLister

Reputation: 10300

Return a sorted iterator of dictionaries based on the keys used for obtaining these dictionaries

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?

Upvotes: 1

Views: 148

Answers (2)

abarnert
abarnert

Reputation: 365707

Yes, it works.

Keeping a sorted collection in place of keeping list_b and sorting it on the fly will improve efficiency—but of course it may reduce efficiency elsewhere that matters more.

There's no other way to improve algorithmic complexity—dict lookups are constant-time, and iterating a list is as fast as iterating anything could possibly be.

You might be able to speed things up by a small constant factor by avoiding the need to hash each (a, b, c) tuple in various different ways, but I doubt that will make much difference.

You can speed things up by a few opcodes by various micro-optimizations related to variable scope and whether you yield values or return a generator, but it's hard to imagine that would ever matter.

Upvotes: 1

the paul
the paul

Reputation: 9161

Yes, it should, assuming you want the ordering of b elements that the default sorted() imposes.

Upvotes: 1

Related Questions