I have the following dictionary:
dict = {'Sex':['Male','Male','Female','Female','Male'],
'Height': [100,200,150,80,90],
'Weight': [20,60,40,30,30]}
I'd like to be able to filter that dictionary using a condition on one key. For example, if I want to keep Male only:
new_dict = {'Sex':['Male','Male','Male'],
'Height': [100,200,90],
'Weight': [20,60,30]}
You can use a dict comprehension and check for the items at the corresponding index at key 'Sex' while building the value lists:
d = {k: [x for i, x in enumerate(v) if dct['Sex'][i]=='Male']
for k, v in dct.items()}
print(d)
# {'Sex': ['Male', 'Male', 'Male'],
# 'Weight': [20, 60, 30],
# 'Height': [100, 200, 90]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With