如何使用Python获取字典中只包含键x, y, w和z的最大值?
my_dict = {"a":0, "b":5, "c":3, "x":4, "y":3, "w":2, "z": 1}
谢谢。
如何使用Python获取字典中只包含键x, y, w和z的最大值?
my_dict = {"a":0, "b":5, "c":3, "x":4, "y":3, "w":2, "z": 1}
谢谢。
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"]))
输出:
4
max(my_dict[i] for i in ["x", "y", "w", "z"])
就可以了。你甚至可以使用元组,因为它是不可变的。max(my_dict[i] for i in ("x", "y", "w", "z"))
- NinjaKitty您可以创建一个临时字典来保存您的值,然后在该字典中搜索您想要的值。
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)])
tmp_tpl = [(i, my_dict[i]) for i in ["x", "y", "z", "w"]]
max
:out = max(tmp_tpl, key= lambda x:x[1])