J.Agusti
J.Agusti

Reputation: 173

Python-Remove empty list from dictionary from a dictionary

I have a dictionary that contains another dictionary that containst a list. I know it is a nightmare, but I use it in order to classify it properly.

L = {}
for s in range(N):
    L[s] = {}
    for a in A[s]:
        L[s][a] = []
        for i in x:
            if (whatever condition for i):
                L[s][a].append(i)

So, my problem is that this code creates a list for each a for each s. Then, if a certain condition is fulfiled then this list is fulled with elements. However, if this condition is not fulfiled, the list remains empty. And this fact, the empty list, causes me serious problems in the following computations, therfore I need to remove that list.

To sum it up, I would need to get it from:

EDIT:

0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001: []}, 1:...

to:

0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001:}, 1:....

I there any way? I tried the .remove() and del, but I didn't work.

Upvotes: 0

Views: 1092

Answers (2)

Mike Müller
Mike Müller

Reputation: 85562

Add only keys for lists that have content in the first place:

L = {}
for s in range(N):
    L[s] = {}
    for a in A[s]:
        for i in x:
            if (whatever condition for i):
                L[s].setdefault(a, []).append(i)  # new list only if there is content

No need to remove them.

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71471

You can use recursion to remove the key-value pair whose value is an empty list:

s = {0: {0.0: [0.10000000000000001, 0.30000000000000004], 0.10000000000000001: []}}
def new_s(s):
   return {a:(b if not isinstance(b, dict) else new_s(b)) for a, b in s.items() if b}

Output:

{0: {0.0: [0.1, 0.30000000000000004]}}

Upvotes: 2

Related Questions