Home > OS >  How can I get the key from value that could either be inside a list or not?
How can I get the key from value that could either be inside a list or not?

Time:10-16

Here is my code for returning the key with most number of values. I'm trying to return 'd' but I cant seem to figure out how. When I tried the list method, it says dingo is not in a list because dingo is in a list with 2 other values.

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

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


#Code to find the key with most number of values

def biggest(aDict):
    biggest = 0
    num =0
    alphabet = ""
    for x in aDict:
        for y in aDict[x]:
            num  = 1
        if num > biggest:
            biggest = num
            alphabet = y
        num = 0
    print(biggest, alphabet)
    
    ################
    #code to get key associated with value here
    ##############
    
biggest(animals)    

CodePudding user response:

Try this:

def biggest(aDict):
    alphabet = max(aDict.items(), key=lambda x: len(x[1]))[0]
    print(len(aDict[alphabet]), alphabet)

# OR

def biggest(aDict):
    alphabet = max(aDict.items(), key=lambda x: len(x[1]))
    print(len(alphabet[1]), alphabet[0])

# OR

def biggest(aDict):
    alphabet, items = max(aDict.items(), key=lambda x: len(x[1]))
    print(len(items), alphabet)
  • Related