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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With