Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of C++ begin() and end() for custom classes

Say you have a dictionary whose keys are integers. The values are also dictionaries whose keys are strings and whose values are numpy arrays. Something like:

custom = {1: {'a': np.zeros(10), 'b': np.zeros(100)}, 2:{'c': np.zeros(20), 'd': np.zeros(200)}}

I've been using this custom data structure quite a lot in the code, and every time I need to iterate over each of the rows in the numpy arrays of this structure, I have to do:

for d, delem in custom.items():
    for k, v in delem.items():
        for row in v:
            print(row)

Is it possible to encapsulate this behavior in functions à la C++ where you can actually implement custom begin() and end()? Also, the iterator should also have information about the keys in their corresponding dictionaries. I envision something like:

for it in custom:
    d, e, row = *it
    # then do something with these
like image 675
aaragon Avatar asked Nov 22 '25 08:11

aaragon


1 Answers

There are multiple ways to do this. yield may be the simplest as it does the heavy lifting of building an interator class for you.

def custom_dict_iter(custom):
    for d, delem in custom.items():
        for k, v in delem.items():
            for row in v:
                yield d, k, row

for d, k, row in custom_dict_iter(my_custom_dict):
    print(d, k, row)
like image 181
tdelaney Avatar answered Nov 23 '25 21:11

tdelaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!