开发者

Find minimum element in a dictionary of dictionaries

I need to find what element of apple has the minimum size.

Tnx for all answers. But there is one problem: I use Python 2.4.2 (I can't change it) and function min haven't key arg. 开发者_如何学PythonYes, I need key of apple

apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}}


import operator
min(apple.values(), key=operator.itemgetter('size'))

will return you

{'color': 'green', 'size': 10}

UPDATE: to get the index:

min(apple, key=lambda k: apple[k]['size'])


Python has a very nice parameter for the min function that allows using an arbitrary function to be minified instead of just using comparison on the elements:

result = min(apple.values(), key=lambda x:x['size'])

The key parameter replaced in most cases the older idiom of decorate-process-undecorate that could have been applied here:

result = min((x['size'], x) for x in apple.values())[1]

If instead you want to know the number (key) of the apple (it's not clear in the question) then:

result = min(apple.keys(), key=lambda x:apples[x]['size'])

or (old style)

result = min((apples[x]['size'], x) for x in apple.keys())[1]


Use min with a custom key function that returns the size of each item.

apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}}
print min(apple.keys(), key=lambda k, a=apple: a[k]['size'])

Which prints:

2

P.S. Since apple is a collection I would make it plural -- apples.


Don't know if it's the fastest way to do it, but anyway:

>>> apple = [ {'size':12, 'color': 'red' }, { 'size':10, 'color':'green'} ]
>>> a = dict(map(lambda apple: (apple['size'], apple), apple))
>>> a
{10: {'color': 'green', 'size': 10}, 12: {'color': 'red', 'size': 12}}
>>> min = a[min(a.keys())]
>>> min
{'color': 'green', 'size': 10}


def get_min(apple):
    L = apple.values()
    m = L[0]
    for item in L:
        if item['size'] < m['size']:
            m = item
    return m

P.S. Not very pythonic but linear time


min(map(lambda a:[apple[a]['size'],a], apple))[1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜