简体   繁体   中英

Storing tuple from generator in dictionary in Python

I have a generator function which computes some slice positions in a numpy array as follows:

import numpy as np
from itertools import product

def __get_slices(data_shape, start, offset, width, patch_size):
    start_indices = [range(start[d] - offset if (start[d] - offset) >= 0 else 0,
                           start[d] - offset + width
                           if (start[d] - offset + width) <= data_shape[d]
                           else data_shape[d])
                     for d in range(len(data_shape))]

    start_coords = product(*start_indices)

    for start_coord in start_coords:
        yield tuple(slice(coord, coord + patch_size) for coord in start_coord)

Now I would like to keep this generated tuple in a dictionary which barfs with a TypeError exception because I am guessing that the slice object is mutable . Is there a way to make it immutable through some python functionality and be able to store it in a dictionary?

On python2.7, I get the following error when trying to assign it to a dictionary:

TypeError: unhashable type

Indeed, slice() objects are unhashable, on purpose , to make sure that dict[slice] = something raises an exception:

>>> d = {}
>>> d[42:81] = 'foobar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'slice'

You'll have to settle for a different object and create slices from those later . Store tuples, for example:

yield tuple((coord, coord + patch_size) for coord in start_coord)

and turn those into slices later when you need to apply these, with slice(*tup) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM