-1

So I have a custom function that returns a default dict. This is how the value is currently returned as:

defaultdict(<function multi_level_dict at 0x0000014E2E099A60>, {'a': 1, 'b': 2})

How can I turn this value into:

{'a': 1, 'b': 2} 

Preferably without using a for/while loop.

martineau
  • 119,623
  • 25
  • 170
  • 301
python_help
  • 121
  • 1
  • 12
  • use `dict(your_default_dict)`. Note that it is really not necessary in order to work with the defaultdict. – buran Dec 10 '21 at 16:57
  • You could make a subclass of `defaultdict` that replaces the stringification logic with that of `dict`. This will work even for the recursive case. – o11c Dec 10 '21 at 18:06

1 Answers1

1

You can construct a regular dict from a defaultdict:

>>> d
defaultdict(<class 'int'>, {'a': 1, 'b': 2})
>>> dict(d)
{'a': 1, 'b': 2}

Note that if the dict is nested such that some of the values are themselves defaultdicts, converting the top level dict won't do anything to those nested values.

Samwise
  • 68,105
  • 3
  • 30
  • 44