Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a dictionary of lists in Python

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]}
like image 632
user2475110 Avatar asked Feb 05 '26 09:02

user2475110


1 Answers

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]}
like image 72
Moses Koledoye Avatar answered Feb 07 '26 22:02

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!