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 find the list with most elements in the items of a dict?

Say that I have

function(Dict[str, List[str]] -> List[str]

how could I return a list that contains the str in the Dict with most elements in the list?

function({'a':['1','2'], 'b':['1'], 'c':['1', '2']})

['a', 'c']

The function should be able to still return the str even if more than one str has the most elements in the list just like the above example. Thank you very much in advance!

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 :

Get the max length first, then loop over the elements to filter those that have the max length:

def get_max(d):
    max_len = max(map(len,d.values()))
    return [k for k,v in d.items() if len(v)==max_len]

get_max({'a':['1','2'], 'b':['1'], 'c':['1', '2']})
# ['a', 'c']
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