简体   繁体   中英

Remove elements from key in Python dictionary

I have a procedure that finds the key that holds the highest number of items in the dictionary. How do i remove the elements in the dictionary so it would only print out

*UPDATE: I just found out that my procedure was incorrect. I was trying to find the key that holds the most items, then return the corresponding key

Goal:

'd'

bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird']}

bird['d'] = ['Finch']
bird['d'].append('Owl')
bird['d'].append('Penguin')

def func(a):
    stor =[]
    for itterate in a.items():
        stor.append(itterate)
    return max(stor)


print func(bird)

Current output:

('d', ['Finch', 'Owl', 'Penguin'])

Sorting the keys on the len() of their values would get you desired results.

>>> bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird'], 'd': ['kiwi', 'Crow', 'Sparrow']}

>>> print sorted(bird.keys(), key = lambda x:len(bird[x]))[-1]
>>> d

And you could embed this line in your function as :

bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird']}

bird['d'] = ['Finch']
bird['d'].append('Owl')
bird['d'].append('Penguin')

def func(a):
    return sorted(bird.keys(), key = lambda x:len(bird[x]))[-1]

print func(bird)

Or as Padraic suggested, Using the max function along with lambda would get your job done in minimal overhead :

def func(a):
    return max(bird.keys(), key = lambda x:len(bird[x]))

Sorting is most certainly not the way to get what you need, you want the key whose value is the longest list so use max on dict.items using the length of the values as the key to max then return the first element :

def func(d):
    return max(d.iteritems(), key=lambda x: len(x[1]))[0]

Output:

In [4]: func(bird)
Out[4]: 'd'

You can also do the lookup in the lambda but items is probably the fastest:

def func(d):
    return max(d, key=lambda x: len(d[x]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM