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

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

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

Be the animals dictionary defined above. The function applied to it should 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's very poorly written. Is there another way to solve the problem?

    
asked by anonymous 22.04.2018 / 01:48

1 answer

4

Looking at your code a bit I see two things to point out:

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

  • Saving the list of all sizes to find the maximum by calling max becomes inefficient. More efficient would be to save the larger one as you compare.

Considering these 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 based on the size of the lists for 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 this example on Ideone

Note that I implemented the lambda comparison function to be shorter. In this, for each element x , the comparison was done by len(aDict[x]) , that is, by the size of the value related to that key.

    
22.04.2018 / 03:55