python – TypeError: dict_keys object does not support indexing

python – TypeError: dict_keys object does not support indexing

Clearly youre passing in d.keys() to your shuffle function. Probably this was written with python2.x (when d.keys() returned a list). With python3.x, d.keys() returns a dict_keys object which behaves a lot more like a set than a list. As such, it cant be indexed.

The solution is to pass list(d.keys()) (or simply list(d)) to shuffle.

Youre passing the result of somedict.keys() to the function. In Python 3, dict.keys doesnt return a list, but a set-like object that represents a view of the dictionarys keys and (being set-like) doesnt support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.

python – TypeError: dict_keys object does not support indexing

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

Leave a Reply

Your email address will not be published.