0

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]

wieluk
  • 13
  • 2
  • It is not clear what you really want. If we are to compare the successive keys, i, to the i-th element of each list values, should not the expected result here be `[1, 2]`? – aichao Jun 12 '22 at 13:52
  • I want to compare each element for a list of every key. {1: [10, 5, 1], 2: [2, 3, 4]} this for example should return [2,2,1] sorry that it is so confusing I don't know how to handle this problem – wieluk Jun 12 '22 at 13:56

3 Answers3

1

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]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

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]
sourin_karmakar
  • 389
  • 3
  • 10
  • Thanks this seems to work. How does it handle same values? for example d = {1:[1,2,3], 2:[1,5,3], 3:[5,2,3]}. Also I think you made a typo with xl or xt – wieluk Jun 12 '22 at 14:05
0

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)

Dante
  • 165
  • 8