Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering a dictionary of dictionaries by a value

I have a small example of a nested dictionary (in my case a collections defaultdict):

all_dict = {'d1': {'a': 2, 'b': 4, 'c': 10}, 
            'd2': {'a': 1, 'b': 23,'c': 0},
            'd3': {'a': 4, 'b': 12,'c': 4},
            'd4': {'a': 0, 'b': 4, 'c': 3},
            'd5': {'a': 4, 'b': 0, 'c': 1}}

And I would like to filter all the zero values in all_dict. In my real data, the nested dictionaries are very big. I would like any general "pythonic" solution.
I tried some comprehension but I failed.
I would like some like:

all_dict_filtered = 
           {'d1': {'a': 2, 'b': 4, 'c': 10}, 
            'd2': {'a': 1, 'b': 23},
            'd3': {'a': 4, 'b': 12,'c': 4},
            'd4': {'b': 4, 'c': 3},
            'd5': {'a': 4, 'c': 1}}

Any tip would be great.
Thank you for your time and attention.
Paulo

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have this but is ugly:

    filtered = defaultdict(dict)
    for k1, v1 in all_dict.items():
        for k2, v2 in v1.items():
            if v2 > 0:
                filtered[k1] = filtered.get(k1, {})
                filtered[k1][k2] = v2
defaultdict(dict,
            {'d1': {'a': 2, 'b': 4, 'c': 10},
             'd2': {'a': 1, 'b': 23},
             'd3': {'a': 4, 'b': 12, 'c': 4},
             'd4': {'b': 4, 'c': 3},
             'd5': {'a': 4, 'c': 1}})

>Solution :

Simple one-liner using dict comprehensions:

import pprint

all_dict = {
    'd1': {'a': 2, 'b': 4, 'c': 10},
    'd2': {'a': 1, 'b': 23, 'c': 0},
    'd3': {'a': 4, 'b': 12, 'c': 4},
    'd4': {'a': 0, 'b': 4, 'c': 3},
    'd5': {'a': 4, 'b': 0, 'c': 1}
}

pprint.pprint({k: {key: value for key, value in v.items() if value != 0} for k, v in all_dict.items()})

Output:

{'d1': {'a': 2, 'b': 4, 'c': 10},
 'd2': {'a': 1, 'b': 23},
 'd3': {'a': 4, 'b': 12, 'c': 4},
 'd4': {'b': 4, 'c': 3},
 'd5': {'a': 4, 'c': 1}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading