How to fix Python yaml.representer.RepresenterError: ('cannot represent an object', defaultdict(<class 'list'>, ....


You are trying to yaml.safe_dump() an object which is (or contains) a defaultdict, e.g.:

import yaml
import collections


which results in the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/uli/.local/lib/python3.10/site-packages/yaml/", line 269, in safe_dump
    return dump_all([data], stream, Dumper=SafeDumper, **kwds)
  File "/home/uli/.local/lib/python3.10/site-packages/yaml/", line 241, in dump_all
  File "/home/uli/.local/lib/python3.10/site-packages/yaml/", line 27, in represent
    node = self.represent_data(data)
  File "/home/uli/.local/lib/python3.10/site-packages/yaml/", line 58, in represent_data
    node = self.yaml_representers[None](self, data)
  File "/home/uli/.local/lib/python3.10/site-packages/yaml/", line 231, in represent_undefined
    raise RepresenterError("cannot represent an object", data)
yaml.representer.RepresenterError: ('cannot represent an object', defaultdict(<class 'list'>, {}))


You need to add a custom representer to implicitly convert the defaultdict to a dict.

Before running yaml.safe_dump(), add the following lines:

import collections
from yaml.representer import Representer

yaml.SafeDumper.add_representer(collections.defaultdict, Representer.represent_dict)

Now, the yaml.safe_dump() call should work perfectly:

yaml.safe_dump(collections.defaultdict(list)) # Returns'{}\n'