Search code examples
pythontupleshashable

Dict to tuple : why does it not take all values?


I converted a dictionary to tuple so it can be hashable.

DATA_ILLUMINANTS = {
'LED': tuple({
    380.0: 0.006,
    385.0: 0.013,
    ...
    780.0: 0.108,})
    }

When I print the tuple, there is not the second column of data, it is :

(380.0, 385.0, 390.0, 395.0, 400.0, ... , 780.0)

Any idea why ?

I use the 'LED' tuple in another code that return me the following error : AttributeError: 'tuple' object has no attribute 'shape' and I suppose this is because data are missing in the tuple.


Solution

  • Iterating over a dict (which is what e.g. tuple() does) iterates over the keys.

    You'll want tuple({...}.items()) to get a tuple of 2-tuples.

    >>> x = {1: 2, 3: 4, 5: 6}
    >>> tuple(x)
    (1, 3, 5)
    >>> tuple(x.items())
    ((1, 2), (3, 4), (5, 6))
    >>>