adi adi - 3 months ago 8
Python Question

Filter out all lists of a dictionary based on a condition applied to one of the lists

I have this dictionary:

d={'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'], 'weight': [165, 189,
220, 141, 260, 174], 'height': [66, 71, 72, 68, 58, 62]}


And I want to filter out all its lists so that they contain only the items that correspond to a height of greater than 70.

I know how to filter lists individually. For instance, the height list:

d["height"]=[height for height in d["height"] if height>70]


And that will return the dictionary with the height list filtered out:

{'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'], 'weight': [165, 189,
220, 141, 260, 174], 'height': [71, 72]}


However, that's not what I want. What I want is:

{'names': ['Amir', 'Matt'], 'weight': [189,220], 'height': [71, 72]}


Anyone can think of how to do this?

Answer

You can use dictionary comprehension.

d = {
    'names': ['Mark', 'Amir', 'Matt', 'Greg', 'Owen', 'Juan'],
    'weight': [165, 189, 220, 141, 260, 174],
    'height': [66, 71, 72, 68, 58, 62]
}

filtered_dict = {
    key: [value for i, value in enumerate(d[key]) if d['height'][i] > 70]
    for key in d
}
print filtered_dict  # {'names': ['Amir', 'Matt'], 'weight': [189, 220], 'height': [71, 72]}