Melanie
Melanie

Reputation: 13

Determining Key with Most Values

dictionary = {"key1": ["Item1", "Item2"], "key2": ["Item3", "Item4"]}

Working with the above dictionary, trying to iterate through it and return the key with most values.

I was trying this:

def most_values(a):
    return max(a, key=a.get)

Which isn't bad though it's going to return whatever key it checks first. Next I tried:

def most_values(a):
    count = 0
    high = ""
    for t in a:
        if len(a[t]) > count:
            count += 1
            high = t
    return high

But it does the same and will return whatever key it iterated through first. It's also not a very elegant looking solution.

What's the most Pythonic way of going about this?

Upvotes: 1

Views: 67

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

The problem with:

return max(a, key=a.get)

is that here the key will return the actual list and in Python lists are compared lexicographically, so not by length (there are things to say for both ways to compare lists, but they decided to sort lexicographically). You can however easily modify this with:

def most_values(a):
    return max(a, key=lambda x:len(a[x]))

This is probably the most Pythonic way since it is declarative (you do not have to think how the maximum is calculated), elegantly, readable and has no side effects.


The problem with your second approach is that you should set count to the new len(a[t]), not increment it. So you can fix it like:

def most_values(a):
    count = -1
    high = None
    for key,val in a.items():
        if len(val) > count:
            count = len(val) # semantical error in your code
            high = key
    return high

Upvotes: 4

Nullman
Nullman

Reputation: 4279

how about this:

sorted(dictionary.iteritems(), key=lambda x:len(x[1]), reverse=True)[0][0]

sorted() sorts stuff. dictionary.iteritems() is an iterator for key:value pairs in the dict. key will receive such a pair and use the 2nd item in it (the value) as the thing its comparing. reverse=True will make it sort from big to small. the first [0] will return the "biggest" key value pair and the second [0] will return the key

or go with Willem Van Onsem's idea because its much cleaner

Upvotes: 2

Related Questions