Determine the key of a dictionary that contains the highest amount of values

Asked

Viewed 948 times

3

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}

animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')

Be the dictionary animals defined above. The function applied to it must return the key "d":

biggest(animals)

result: ’d'

My code:

def biggest(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: The key with the largest number of values associated with it
    '''


    maior = []
    key_maior = []
    for i in aDict.keys():
        #print(i)
        key_maior.append(i)
        maior.append(len(aDict[i]))
    #print(key_maior)
    #print(maior)



    maximo = max(maior)
    #print(maximo)
    #print(maior.index(maximo))
    return key_maior[maior.index(maximo)]


animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}

animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')


print(biggest(animals))

The code works but I think it is badly written. There is another way to solve the problem?

1 answer

4

Analyzing your code a little I see two things to point out:

  • for i in aDict.keys(): - Here you are iterating over the keys, but then accessing the values in len(aDict[i]). It would be better to iterate on the items that already have access to both: for chave, valor in aDict.items():

  • Save list of all sizes to find the most calling max becomes inefficient. More efficient would be to store the larger as it compares.

Considering those two points you said, your program would look like this:

def biggest(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: The key with the largest number of values associated with it
    '''

    maior = 0
    chave_maior = None
    for chave, valor in aDict.items():
        if len(valor) > maior:
            maior = len(valor)
            chave_maior = chave

    return chave_maior

See this example in Ideone

Now to be truly idiomatic in Python you have to make use of the tools that already exist. The native function max allows you to pass a function to indicate how the elements are compared to find the maximum. You can make use of this by indicating that the comparison is made based on the size of the lists of each entry:

def biggest(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: The key with the largest number of values associated with it
    '''

    return max(aDict, key=lambda x: len(aDict[x]))

See also this example in Ideone

Note that I implemented the comparison function with a lambda to be shorter. This one said that for each element x the comparison was made by len(aDict[x]), that is, by the size of the value of that key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.