How to compare the value in the dictionary of python


#1

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)


#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[0][1]
print smallest
>>>(7, 3)

–Mitch


#3

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

#4

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])[1]

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


#5

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

#6

Thanks for the tip

-M