Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典中的最大值_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 字典中的最大值

Python 字典中的最大值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一本字典看起来像 dic = { "X": 15, "Y": 20, "Z": 2 } 我将为每个值添加字典中的最小值。我写了这个代码 minimum = min(list(dic.values())) dic["X"] = dic["X"] + minimum dic["Y"] = dic["Y"] + minimum dic["Z"] = dic["Z"] + minimum 要求的结果 { "X": 17, "Y": 22, "Z": 4 } 我的代

我有一本字典看起来像

dic = {
   "X": 15, 
   "Y": 20, 
   "Z": 2 
}
我将为每个值添加字典中的最小值。我写了这个代码

minimum = min(list(dic.values()))
dic["X"] = dic["X"] + minimum 
dic["Y"] = dic["Y"] + minimum 
dic["Z"] = dic["Z"] + minimum 
要求的结果

{ "X": 17, "Y": 22, "Z": 4 }
我的代码可以工作,但我认为这不是一个很好的解决方案。有人比我有更好的解决办法

dic = {
   "X": 15, 
   "Y": 20, 
   "Z": 2 
}
minimum = min(dic.values())
for key in dic:
    dic[key] += minimum
print(dic)
输出:

如何使用min():

如果提供了一个位置参数,则该参数应为iterable。这个 返回iterable中最小的项。如果两个或多个位置 如果提供了参数,则最小的位置参数为 返回

dic[key]=value
是就地更改,无需生成新的dict容器。

或使用:

注意:对于
min
,您不需要
列出值;这只会创建一个不必要的列表

{'X': 17, 'Z': 4, 'Y': 22}
min(iterable, *[, key, default ])
min(arg1, arg2, *args[, key ])
minimum = min(dic.values())

dic2 = {x: val + minimum for x, val in dic.items()}