I have a dictionary where each key is a string and value is Pandas's resultSet. I know how to write a list comprehension for it, for example:
myDict = {k: v for k,v in myDict.items() if len(v)>0 }
But what I need to do is to apply some filter not to resultSet itself, but to its elements. I.e. I want to write a comprehension which would do
myDict = {k: v for k,v in myDict.items() if [leave only elements which have field c > 0 inside each resultSet] }
So if I have
[
"key1": [["a":1,"b":-2,"c":-3], ["a":1,"b":-2,"c":3]],
"key2": [["a":1,"b":2,"c":3], ["a":51,"b":-42,"c":43]]
]
I should end up with
[
"key1": [["a":1,"b":-2,"c":3]],
"key2": [["a":1,"b":2,"c":3], ["a":51,"b":-42,"c":43]]
]
..because key1 ' s second row have column with c<0 and then it should be filtered out.
Is it possible to write a sort of comprehension for it or I should switch to regular cycles?
CodePudding user response:
Use nested list comprehension for filter nested dicts:
myDict = {
"key1": [{"a":1,"b":-2,"c":-3}, {"a":1,"b":-2,"c":3}],
"key2": [{"a":1,"b":2,"c":3},{"a":51,"b":-42,"c":43}]
}
myDict = {k: [x for x in v if x['c'] > 0] for k,v in myDict.items()}
#MYousefi super comment - if "c" is not guaranteed
myDict = {k: [x for x in v if x.get("c", -1) > 0] for k,v in myDict.items()}
print (myDict)
{'key1': [{'a': 1, 'b': -2, 'c': 3}],
'key2': [{'a': 1, 'b': 2, 'c': 3}, {'a': 51, 'b': -42, 'c': 43}]}