Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter dictionary for keys with multiple items in a list for value

I have a dictionary with a key-value pair consisting of a key and a value that consists of one or multiple elements of a list. I am looking for a way to filter the dictionary to only include the keys with multiple list elements (more than one).

Example:

dictX = {'cat': [0], 'dog': [1], 'bird': [2,2,2], 'fish': [3,4]}

I want to filter so that the new dictionary would only have ‘bird’ and ‘fish’ as key value pairs, while dropping the ones with a single element in the list value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can just use a dict comprehension and len:

dictY = {key: val for key, val in dictX.items() if len(val) > 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading