3

Input:

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

Desired Output:

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

Note: I wanna iterate through and keep only the key with the maximum value among same keys !! And list of dictionaries should be kept !

DataFlow
  • 33
  • 5

3 Answers3

1

A more concise approach based on @Ioannis' answer

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)

output:

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

Detailed approach:

You can create a dictionary with max values and check with it for each list item. You can implement it using 2 for loops.

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)

output:

[{'C': 1.0}, {'A': 0.5, 'B': 0.9}]
Shivam Agrawal
  • 481
  • 2
  • 12
1

Ioannis's answer should work, but here is a more visual answer if that didn't make sense.

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

Now we store the index of each key max in 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

Now, we have all the max indexes. So, we can go through a new list, say C, and add dicts for the length of A (ie there are the same number of dicts as A)

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

Output (tested on 3.9.4): [{'C': 1.0}, {'A': 0.5, 'B': 0.9}]

KarmaPenny
  • 164
  • 1
  • 13
0
B = {k: max([d[k] for d in A]) for k in A[0]}

If B needs to be within a list, then [B].

0 _
  • 10,524
  • 11
  • 77
  • 109