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

Find key in dictionary with most unique values

I have a dictionary of lists:

dict_one = {'a': ['Hanks', 'Bob', 'Bill'], 'b': ['nation', 'nile', 'Jonas']}

the dictionary above was only an example it could be extremely long

I need to find to the key with the most unique set of names or words.

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

I need both the key and the actual length of the key

So far, I have been able to find the actual length of the unique list pretty easily with the code below:

print(max(len(set(x)) for x in dict_one.values()))

But now I am struggling with finding the key itself. I need to print the length and the key itself as said prior. For example, an output might look like this:

key: a
length: 3

>Solution :

you’re pretty close. did you know that max can take a key the same way that sort can? check this out:

max(dict_one.items(), key=lambda x: len(set(x[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