简体   繁体   中英

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.

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]}}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM