Search code examples
pythondictionarylambdadefaultdict

How to create a new list or set object for an inner dictionary key so that the same object is not repeatedly being updated?


I'm trying to create an inner dictionary that has values stored in a list or set object (using a set for this example).

t = [('Jobs', set()), ('Titles', set())]
inn_d = lambda: dict(t)

And creating a default dictionary and passing inn_d into that.

d = defaultdict(inn_d)

When creating the entries for d and the outer keys, both values for each inner key gets updated.

d['A']['Jobs'].add('Cook')
d['B']['Titles'].add('President')
d
defaultdict(<function <lambda> at 0x0000016691157DC0>, {'A': {'Jobs': {'Cook'}, 'Titles': {'President'}}, 'B': {'Jobs': {'Cook'}, 'Titles': {'President'}}})

When it should be

defaultdict(<function <lambda> at 0x0000016691157DC0>, {'A': {'Jobs': {'Cook'}, 'Titles': set()}, 'B': {'Jobs': set(), 'Titles': {'President'}}})

I know that the same set object for both Jobs and Titles is getting called - I am not sure how to create a new set object when creating the inner dictionary.

Thank you for your help.


Solution

  • Create a new one each time like this:

    def inn_d():
        return {'Jobs': set(), 'Titles': set()}
    

    By the way, named lambdas are bad practice.