python - How to omit keys with empty (non-zero) values -
i have dict { 'a': 'a', 'b': 0, 'c': {} }
, need omit keys have empty values (0 not considered empty). so, output of should { 'a': 'a', 'b': 0 }
.
for { 'a': 'a', 'b': 0, 'c': { 'd': 'd' } }
--> { 'a': 'a', 'b': 0, 'c': { 'd': 'd' } }
;
i tried {k: v k,v in my_dict.items() if not v}
, i'm not sure how preserve 0s;
i'm looking https://lodash.com/docs/4.17.4#omitby
you can write function takes predicate filtering based on values:
def omit_by(dct, predicate=lambda x: x!=0 , not x): return {k: v k, v in dct.items() if not predicate(v)} dct = { 'a': 'a', 'b': 0, 'c': {} } print(omit_by(dct)) # {'a': 'a', 'b': 0} dct = {'a': 'a', 'b': 0, 'c': { 'd': 'd' } } print(omit_by(dct)) # {'a': 'a', 'b': 0, 'c': {'d': 'd'}}
simply change predicate suites you.
Comments
Post a Comment