0
votes

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.

1
This definitely will also fail in Python 2 in the same way... A question, what do you expect hist[0] to do???juanpa.arrivillaga
what is your hist[0], Is it a list or integer value ?Vikas P
hist is an int (1, 2, or 3).Ollie
Note, hists = list(my_dict.copy().keys()) is an unnecessarily complicated way of doing hists = list(my_dict)juanpa.arrivillaga
Complicated operation that needs work. .keys()) works in Python 2.Life2Day

1 Answers

0
votes

When you do hist in hists, you are getting the actual element, not the index. So for your example, hists will have [1,2,3] and hist variable will have 1,2 and 3 value. And 1[0] will obviously give you an error because 1 is an int, and you can't subscript an int. And you don't have to worry about max, that would have been a problem in a while loop, not for a loop.

To iterate over the dictionary, when you're not deleting or adding new keys is to simply do the following

for key in my_dict:
    curr_val = my_dict[key]   #This will give you the value at key

And if you only want to find max key then this can be done rather easily

max_key = max(list(my_dict))