[英]after a for loop that give me differents dictionary how to find the dictionary with the max value?
我想在 for 循环后找到具有最大值的字典
我有一个列表 L,在 for 循环之后(列表中的 L :) 给我 3 个字典:
{a:1}
{b:2}
{c:3}
如何打印 {c:3}
I try the function.append to create a nested dictionary and try to do a loop with this nested dict but the function append doesn't work for dict.
如何打印:{{a:1}, {b:2}, {c:3}}
或者如何打印出所有字典的列表? [{a:1}, {b:2}, {c:3}]
以及如何打印:{c:3}
谢谢
您可以尝试进行更新,以便 dicts 连接,例如:
dict1 = {'a':1}
dict2 = {'b':2}
dict3 = {'c':3}
dict2.update(dict3)
dict1.update(dict2)
这应该导致一个单一的字典
>>>>print(dict1)
>>>>{'a':1,'b':2,'c':3}
之后你可以创建一个 function 或者你可以做一个 for 循环来迭代实际的字典,我试过这样的事情:
def maxValueDict(values): #Function that recives a dict
act = 0 #use to evaluate
max_value= {} #dict that will become the max value
for key,value in values.items(): #we iterate the items
if value > act: #if the value is bigger than the actual value
act = value #we update the actual value
max_value.clear() #we clean the dict
max_value[key] = value #we add the new key and the value
return max_value #return the final value
所以最终的结果会是这样的:
maxValue = maxValueDict(dict1)
>>print(dict1)
>>{'a': 1, 'b': 2, 'c': 3}
>>print(maxValue)
>>{'c':3}
您可以考虑以下代码:
objects = [{"a": 1},
{"b": 2},
{"c": 3}]
to_print = objects[0]
for obj in objects:
key = list(obj.keys())[0] # Takes the first key of object, in this case, "a", "b", or "c"
tp_key = list(to_print.keys())[0]
if obj[key] > to_print[tp_key]:
to_print = obj
print(obj)
Output: {'c': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.