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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With