Search code examples
pythondictionarykey

Adding missing keys in dictionary in Python


I have a list of dictionaries:

L = [{0:1,1:7,2:3,4:8},{0:3,2:6},{1:2,4:6}....{0:2,3:2}]. 

As you can see, the dictionaries have different length. What I need is to add missing keys:values to every dictionary to make them being with the same length:

L1 = [{0:1,1:7,2:3,4:8},{0:3,1:0,2:6,3:0,4:0},{0:0, 1:2,3:0,4:6}....{0:2,1:0,2:0,3:2,4:0}], 

Means to add zeros for missing values. The maximum length isn't given in advance, so one may get it only iterating through the list.

I tried to make something with defaultdicts, like L1 = defaultdict(L) but it seems I don't understand properly how does it work.


Solution

  • a bit of caution: changes L

    >>> allkeys = frozenset().union(*L)
    >>> for i in L:
    ...    for j in allkeys:
    ...        if j not in i:
    ...            i[j]=0
    
    >>> L
    [{0: 1, 1: 7, 2: 3, 3: 0, 4: 8}, {0: 3, 1: 0, 2: 6, 3: 0, 4: 0}, {0: 0, 1: 2, 2:
     0, 3: 0, 4: 6}, {0: 2, 1: 0, 2: 0, 3: 2, 4: 0}]