Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversed OrderedDict TypeError

I have an ordered dictionary and I am trying to go through it in reverse order, basically starting from the last (key, value) inserted.

dicts = OrderedDict()
...
for key, value in reversed(dicts.items()):

The above code works fine when I use PyCharm with Python 3.5.1, but when I place it on codefights, using their Python 3 interpreter (not sure what exact version), I get the error below for the for loop implementation:

TypeError: argument to reversed() must be a sequence

Why is this error happening and how can I fix it?

like image 283
user1179317 Avatar asked Jan 05 '23 08:01

user1179317


1 Answers

As per the docs, OrderedDict.items() only supported reversed from 3.5, so I expect it's an older version.

One way you could fix it is convert to a list first:

for key, value in reversed(list(dicts.items())):
     ...

NB: as per the comments, dicts.items() should be memory efficient but list(dicts.items()) will definitely create a new list with length the number of items in dicts. Most of the time this should be fine, but for very large dicts this will see a O(N) memory usage hit which may be significant.

like image 97
daphtdazz Avatar answered Jan 14 '23 04:01

daphtdazz