Search code examples
pythondeep-copy

Without using the copy library create a copy of a nested dictionary (Python)


I've got a map of this form:

Weekday -> Object -> Integer

I've tried to do this but am getting some issues down the line to do with a key not existing. The error could exist elsewhere in the code. However, could someone perform a little sanity check for me please?

def deepCopy(self, dictToCopy):
    copy = {"Monday":{}, "Tuesday":{}, "Wednesday":{}, "Thursday":{}, "Friday":{}}
    for day, dicts in dictToCopy.items():
        for object, count in dicts.items():
        copy[day][object] = count
    return copy

Solution

  • How about:

    def deepCopy(dictToCopy):
        days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        return {
            day: {obj: count for obj, count in dictToCopy.get(day, {}).items()}
            for day in days
        }
    
    
    def test_deepCopy():
        src = {
            "Monday": {
                "thing1": 1,
                "thing2": 3,
            },
            "Wednesday": {
                "thing3": 4,
                "thing5": 1,
            },
        }
    
        expected = {
            "Monday": {
                "thing1": 1,
                "thing2": 3,
            },
            "Tuesday": {},
            "Wednesday": {
                "thing3": 4,
                "thing5": 1,
            },
            "Thursday": {},
            "Friday": {},
        }
    
        res = deepCopy(src)
        assert res == expected
    
        # verify that res is a *copy* -- changing value in src does not
        # change value in res
        src["Monday"]["thing1"] = 2
        assert res == expected
    

    If you have pytest handy you can run the test case by just running example.py, assuming you've saved the above code in example.py.