-1

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.

гиви
  • 79
  • 7
  • Post code you used to convert and what you expected to get. – Tarik Apr 30 '21 at 07:54
  • 2
    When you iterate over a dictionary, you iterate over its _keys_. What output were you expecting - `tuple({...}.items())`, maybe? – jonrsharpe Apr 30 '21 at 07:54
  • 1
    The "tuple object has no attribute 'shape'" error is symptomatic of that code needing a Numpy array, but that's another can of worms. – AKX Apr 30 '21 at 07:56
  • Dict values don't have to be hashable. Only the keys do. You could use the dict as is; no need to convert it to a tuple. – John Kugelman Apr 30 '21 at 07:57
  • If you're converting a dict literal to a tuple, as in your example, why not simply use a tuple literal in the first place? – Roel Schroeven Apr 30 '21 at 08:47

2 Answers2

2

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))
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172
1

tuple() will iterate through the given object, here a dict. The dict iterate over the keys, this is why. You can force it to iterate over the items: tuple({ 380.0: 0.006, 385.0: 0.013, ... 780.0: 0.108,}.items() )

pygame
  • 121
  • 5