Answer the question
In order to leave comments, you need to log in
How to remove all null elements from a dictionary?
There is a dictionary like: {user1 { var1: 2, var2: 0, var3: 1, var4: 0}, user2 {var1: 0, var2: 1, var3: 0, var4: 0}, user3{ var1:1, var2 : 0, var3:0, var4:0}}
How to remove all "subdictionary" keys with null values, so that it turns out:
{user1 { var1: 2, var3: 1}, user2 {var2: 1}, user3{ var1:1}}.
I tried, but I could only implement the function where the user is passed. Such an implementation is unacceptable. the number of users is large.
PS There would be no problems if the dictionary was "one-dimensional"
Answer the question
In order to leave comments, you need to log in
You need to go through it recursively.
>>> def f(d):
... for i in set(d):
... e = d[i]
... if isinstance(e, dict):
... f(e)
... elif e == 0:
... del d[i]
...
>>> d = {'user1': {'var1': 2,
... 'var2': 0,
... 'var3': 1,
... 'var4': 0},
... 'user2': {'var1': 0,
... 'var2': 1,
... 'var3': 0,
... 'var4': 0},
... 'user3': {'var1': 1,
... 'var2': 0,
... 'var3': 0,
... 'var4': 0}}
>>>
>>> f(d)
>>> d
{'user3': {'var1': 1}, 'user2': {'var2': 1}, 'user1': {'var1': 2, 'var3': 1}}
>>>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question