AttributeError: 'defaultdict' object has no attribute 'items'
>>> from collections import defaultdict
>>> dd = defaultdict(list)
>>> dd
<defaultdict object at 2006e7d0>
>>> dd.items()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'defaultdict' object has no attribute 'items'
defaultdict doesn't have an items() method, so iterating over it is a bit of a pain in the neck. Also no __repr__(), but that's not totally necessary I guess.
python-stdlib/collections-defaultdict: Add items() function.
Summary
This PR adds the items() functions to collections.defaultdict, acting as a simple proxy to the underlying dictionary container.
This fixes #350.
The package's version number was bumped up by 0.1.0 since a new function was added to the module.
Testing
The added tests in python-stdlib/collections-defaultdict were run successfully both on CPython (with a tweaked import harness) and on MicroPython's git master.
Trade-offs and Alternatives
This adds 81 bytes to the final module. I'm a bit surprised it took that much, but unless it is documented that the backing dictionary can be accessed via self.d when code runs on MicroPython, I don't see any other safe way to enumerate the contents [1].
Generative AI
I did not use generative AI tools when creating this PR.
<hr>
[1]
This trips up MicroPython, for example:
from collections import defaultdict
a = defaultdict.defaultdict(list)
for i in a:
print(i)
On current MicroPython's git master:
$ cd python-stdlib/collections-defaultdict
$ $MICROPYTHON
MicroPython v1.28.0-preview.306.g5c00edcee2.dirty on 2026-03-23; linux [GCC 15.2.1] version
Type "help()" for more information.
>>> from collections import defaultdict
>>> a = defaultdict.defaultdict(list)
>>> for i in a:
... print(i)
...
[]
[]
[]
[]
# `[]` being repeated a fairly large number of times here...
[]
[]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "collections/defaultdict.py", line 20, in __getitem__
MemoryError: memory allocation failed, allocating 260368 bytes
>>>
Whilst this works as expected on CPython 3.14 (and probably earlier versions too):
$ python
Python 3.14.3 (main, Feb 13 2026, 15:31:44) [GCC 15.2.1 20260209] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> a = defaultdict(list)
>>> for i in a:
... print(i)
...
>>>
Can I work on this issue? @xrmx
This seems to still be the case - no "items()" function in the defaultdict module.
Anyone is welcomed to open merge requests in the MicroPython project :)