 # How to compare the value in the dictionary of python

I have a dictionary like this {key: value, key2: value2, key3:value3}. How could I know the smallest number of the Value and also tell me the Key that the Value belongs to.
This is what I did, But it return the smallest key, not the value.

Dictionary = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}
Min(Dictionary)
(5,2)

Here’s one way:

``````Dictionary = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}
dictList=zip(Dictionary.values(),Dictionary.keys())
dictList.sort()
smallest=dictList
print smallest
>>>(7, 3)
``````

–Mitch

1 Like

Here’s a slightly different approach:

``````dictionary = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}

# Get index of smallest value
values = dictionary.values()
smallIndex = values.index(min(values))

# Get the corresponding key
keys = dictionary.keys()
smallKey  = keys[smallIndex]

print smallKey
``````

You could get it down to two lines be using dictionary.values() and dictionary.keys() directly, like so:

``````a = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}

smallIndex = a.values().index(min(a.values()))
smallKey  = a.keys()[smallIndex]

print smallKey
``````
1 Like

Here’s another approach:

``````dict = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}
smallestKey = min([[dict[key],key] for key in dict])
``````

and another approach

``````dict = {(4, 5): (2.733), (5, 2): (2.4533), (6, 2): (4.533), (7, 3): (1.333)}
smallestKey = min(dict, key=dict.get)
``````

-M

2 Likes

Nice one Miguel! Can’t see anyone beating that for brevity.

Sidenote:

Considering one can instantiate a dictionary using dict() it is probably advisable not to name variables “dict”. See for example this case:

``````dict = "foo"
bar = dict(one=1,two=2)
print bar
``````

Thanks for the tip

-M