Search code examples
python-3.xdefaultdict

Creating a defaultdict of a tuple with a list and int


I know to create a defaultdict with default values, i can use the below:

defaultdict(lambda : 0)

and for a defaultdict of tuple with default values, i can use the following:

defaultdict(lambda: (0,0))

But i am struggling with this, how do i create a defaultdict of tuple with a list and an int? I need something like :

{key1:['a','b','c','a'],100),key2:(['a','a','a','a'],2100),(key3:['adds','bas','cs','a'],300),key4:(['a'],30)}

So i need to check for an item in the list, if it is not present, i need to increment the int value. Is my idea of tackling this situation using defaultdict correct??


Solution

  • if you want to be able to do this:

    d["some_key"][1] += 1
    

    even if key doesn't exist and get [set(),1] as a value then do:

    d = collections.defaultdict(lambda : [set(),0])
    
    • Note #1: defaultdict(lambda : 0) is overkill for defaultdict(int)
    • Note #2: I used a list and not a tuple for the default value. Had I used a tuple, I would have had a hard time to increment second item by 1 since tuples are read-only. Note #3: tuple is mostly useful as keys (because they're immutable, thus hashable), not as values, where you can store anything you want, hashable or not.