How to return smallest value in dictionary?

2020-07-09 10:09发布

Let say I have a dictionary of total of fruits:

Fruits = {"apple":8, "banana":3, "lemon":5, "pineapple":2,}

And I want the output to be

["pineapple"]

because pineapple has the least value. Or if i have this:

Colour = {"blue":5, "green":2, "purple":6, "red":2}

The output will be:

["green","red"]

because green and red has both the least value.

So how do I return the smallest value in dictionary?

7条回答
不美不萌又怎样
2楼-- · 2020-07-09 11:14
colors = {"blue":5, "green":2, "purple":6, "red":2}# {"apple":8, "banana":3, "lemon":5, "pineapple":2,}

sorted_items = sorted(colors.items(), key=lambda t: t[1])
print (sorted_items)


min_val = sorted_items[0][1]

for t in sorted_items:
    if t[1] == min_val:
        print(t[0])
    else:
        break




--output:--
[('green', 2), ('red', 2), ('blue', 5), ('purple', 6)]

green
red
查看更多
登录 后发表回答