如何在多个字典中只保留具有全局最大值的键值对?

How to keep only the key-value-pair with the global max value over several dictionaries?

输入:

A= [{'A':0.4, 'B':0.8, 'C':1.0},
    {'A':0.5, 'B':0.9, 'C':0.0}]

期望的输出:

A=[{'C':1.0},{'A':0.5, 'B':0.9}]

注意:我想遍历并只保留相同键中具有最大值的键!并且应该保留字典列表!

B = {k: max([d[k] for d in A]) for k in A[0]}

如果 B 需要在 list 内,则 [B]

基于@Ioannis 回答的更简洁的方法

max_dict = {k: max([d[k] for d in A]) for k in A[0]}
result = [{k: v for k, v in i.items() if v == max_dict[k]} for i in A]
print(result)

输出:

[{'C': 1.0}, {'A': 0.5, 'B': 0.9}]

详细做法:

您可以创建一个包含最大值的字典并检查每个列表项。您可以使用 2 个 for 循环来实现它。

A = [{'A': 0.4, 'B': 0.8, 'C': 1.0},
     {'A': 0.5, 'B': 0.9, 'C': 0.0}]

max_dict = {}

for a_dict in A:
    for key, value in a_dict.items():
        if key not in max_dict or max_dict[key] < value:
            max_dict[key] = value

result = []
for a_dict in A:
    temp_dict = {}
    for key, value in a_dict.items():
        if value == max_dict[key]:
            temp_dict[key] = value
    result.append(temp_dict)

print(result)

输出:

[{'C': 1.0}, {'A': 0.5, 'B': 0.9}]

Ioannis 的答案应该有效,但如果这没有意义,这里有一个更直观的答案。

B={}
for i in range(len(A)):
    d = A[i]
    for key in d:
        if (key not in B): B[key]=i

现在我们将每个key max的index存入B.

for i in range(len(A)):
    d=A[i]
    for key in d:
        if (A[B[key]][key]<d[key]): 
            # A[B[key]][key] gets the index of the max using B[key]
            # then gets the dictionary at that index using A[B[key]], and then
            # then finally gets the value using A[B[key]][key]
            B[key]=i

现在,我们拥有了所有的最大索引。所以,我们可以遍历一个新列表,比如 C,然后添加 长度为 A 的字典(即与 A 有相同数量的字典)

C=[]
for i in range(len(A)):
    C.append({})
for key in B:
    ind = B[key]
    C[ind][key]=A[B[key]][key]

输出(在 3.9.4 上测试):[{'C': 1.0}, {'A': 0.5, 'B': 0.9}]