iamsk
4/4/2016 - 3:22 AM

defaultdict2dict.py

from collections import defaultdict


def defaultdict2dict(d):
    _d = {}
    for k, v in d.items():
        if isinstance(v, defaultdict):
            _d[k] = defaultdict2dict(v)
        else:
            _d[k] = v
    return _d


if __name__ == "__main__":
    temp = defaultdict(lambda: defaultdict(lambda: defaultdict()))
    temp[1][2][3] = 1
    temp[2][3] = 1
    temp[3] = 1
    assert isinstance(temp, defaultdict)
    assert isinstance(defaultdict2dict(temp), dict)