Find the minimum element in a dictionary of dictionaries

I need to find which element applehas a minimum size.

Tnx for all answers. But there is one problem: I am using Python 2.4.2 (I cannot change it), and the function minhas no keyarg. Yes i need a keyapple

apple = {1:{'size':12,'color':'red'},2:{'size':10,'color':'green'}}
+3
source share
6 answers

Python has a very good parameter for a function minthat allows you to use an arbitrary function that needs to be minimized, and not just use element-by-element comparison:

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

The parameter keyin most cases replaced the older idiom decoration-process-undecorate, which could be applied here:

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

() ( ), :

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

( )

result = min((apples[x]['size'], x) for x in apple.keys())[1]
+10
import operator
min(apple.values(), key=operator.itemgetter('size'))

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

UPDATE: :

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

Use minwith a custom function keythat returns the size of each element.

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

What prints:

2

PS Since apple- this is a collection, I would make it plural - apples.

+3
source

I don't know if this is the fastest way to do this, 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}
+1
source
def get_min(apple):
    L = apple.values()
    m = L[0]
    for item in L:
        if item['size'] < m['size']:
            m = item
    return m

PS Not very pythonic, but linear time

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

Source: https://habr.com/ru/post/1793975/


All Articles