The code worked in Python 2, but not in Python 3 and getting:-
TypeError:
'int' object is not subscriptable
Trying to get the length on the dictionary key while going through the loop.
The loop is iterating through each key and seeking to do things before max is reached and when it reaches max. Looking for guidance on why the TypeError and help.
Here is example dictionary with keys: 1, 2, 3.
my_dict = {1: a, 2: b, 3: c}
Setting int with name max because something needs to happen
max = 3
Python 3
hists = list(my_dict.copy().keys())
for hist in hists:
if len(hist[0]) < max - 1: # <-- TypeError: 'int' object is not subscriptable)
print("pass")
elif len(hist[0]) == max:
print("equal max")
Python 3, we need to lock the keys, protecting iteration of key order and doing this by copying to new dictionary. Because python 3 .keys() returns an iterable view , not like python 2. To get the keys in order, we need to convert to a list, which seems to also set the order.
In Python 2, order is set when using .key() and didn’t need to be concern about views. Common to use dictionary keys in loops.
It's ok to use when the dictionary is not being updated in real-time. Found it tends to be more expensive and slower.
hist[0]
to do??? – juanpa.arrivillagahist[0]
, Is it a list or integer value ? – Vikas Phist
is an int (1, 2, or 3). – Olliehists = list(my_dict.copy().keys())
is an unnecessarily complicated way of doinghists = list(my_dict)
– juanpa.arrivillaga