Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Biggest value of (not all) dictionary keys in Python

What's the best way to get the biggest value of only the keys x, y, w and z in the dictionary above using Python?

my_dict = {"a":0, "b":5, "c":3, "x":4, "y":3, "w":2, "z": 1}

Thanks

like image 584
Paulo Fabrício Avatar asked Dec 14 '25 17:12

Paulo Fabrício


2 Answers

You can try this:

my_dict = {"a":0, "b":5, "c":3, "x":4, "y":3, "w":2, "z": 1}
print(max(my_dict[i] for i in ["x", "y", "w", "z"]))

Output:

4
like image 81
Ajax1234 Avatar answered Dec 16 '25 13:12

Ajax1234


You could create a temporary dictionary to hold your values, then search in this dictionary for the value you want.

my_dict = {"a":0,"b":5,"c":3,"x":4, "y":3, "w":2, "z": 1}
newdict = {key:my_dict[key] for key in ['x', 'y','w','z']}
print(newdict[max(newdict, key=newdict.get)])
like image 31
Rkanehisa Avatar answered Dec 16 '25 15:12

Rkanehisa