Home > other >  Python dictionary min value for each element for all keys
Python dictionary min value for each element for all keys

Time:06-12

I have a dict that looks like this:

{1: [1, 2, 3], 2: [4, 5, 6]}

The dictionary can have n keys and the list n values. The lists have always the same length.

I would like to compare each value of all keys with the other values.

For example I want to compare the first value of all keys here 1 and 4. 1 is smaller so the first element in my new list should be 1(the key). Then compare 2 and 5 -> 2 is smaller so add another 1. This should be done for all elements. the list for this example should be [1,1,1]

CodePudding user response:

You can generate a mapping from an index to a key in the dictionary. Then, you can generate the indices where the minima occur using a transpose operation and an argmin operation.

From there, you can translate the generated indices into keys that appear in the dictionary using a list comprehension.

key_indices = {idx: key for idx, key in enumerate(dictionary)}

indices = [min(range(len(lst)), key=lambda x: lst[x]) for lst in zip(*dictionary.values())]

[key_indices[index] for index in indices]

This outputs:

[1, 1, 1]

CodePudding user response:

Please check this solution

import numpy as np

d = {1:[1,2,3], 2:[4,5,6], 3:[5,1,1]}
k = list(d)
xt = np.argmin(np.array(list(d.values())).T, axis=1)
ans = [k[x] for x in xt]
print(ans)

Output

[1, 3, 3]

CodePudding user response:

hope this helps.It works even for more pair but the value array must be the same for all keys

dict={1: [1, 2, 3], 2: [4, 5, 6],3:[1,7,3]}
//considering all values having the same length
keys,values=zip(*dict.items())
new_array=[]
for i in range(len(values[0])):
    max=0
    for key in keys:
        if dict[key][i]>max:
            max=dict[key][i]
    new_array.append(max)
print(new_array)

you can try with dict={1: [1, 2, 3], 2: [4, 5, 6],3:[1,7,3],4:[3,4,9],7:[9,8,7]}

for values with different dimensions

dict={1: [1, 2, 9,5], 2: [4, 5, 6],3:[1,7,3],4:[3,4,9],7:[9,8,7,6,2,1]}
keys,values=zip(*dict.items())
max_length=0
for value in values:
    if len(value)>max_length:
        max_length=len(value)
print(max_length)
new_array=[]
for i in range(max_length):
    
    max=0
    for key in keys:
        try:
            if dict[key][i]>max:
                max=dict[key][i]
        except:
            pass
    new_array.append(max)
print(new_array)

  • Related