Find the most similar number from list of lists in a dictionary python

Question:

I have a dictionary where the values are a list of lists:

dict1 = {"['x1', 'y1']": [['r1', 'r2'], [78, 125]],
    "['x1', 'y1']": [['r1', 'r2'], [77, 112]],
    "['x1', 'y1']": [['r1', 'r2'], [73, 110]],
    "['x2', 'y2']": [['r2', 'r3'], [71, 103]]}

I am also giving a list of lists as input which i want to find in dict1

 input1 = [['r1', 'r2'], [72, 112]]

The first list ['r1', 'r2'] is the same as in dict1 and can still be easily found. But for the second list, i need to find approximate numbers in dict1. So for [72, 112] it’s [73, 110].I don’t understand how to do it

Estimated output I want:

output = { "['x1', 'y1']": [['r1', 'r2'], [73, 110]]}
Asked By: Rory

||

Answers:

Brief about the code.

(1) mini variable is set to the positive infinity to initialize the minimum difference to a high value.
(2) looping through all key-value pairs in the dict1
(3) if value[0] == input1[0]: if this condition satisfy it will check the `abs` value b/w input and dictionary if it is lower than mini it will update the mini value and also output value is updated

Code:

dict1 = {"['x1', 'y1']": [['r1', 'r2'], [78, 125]],
    "['x1', 'y1']": [['r1', 'r2'], [77, 112]],
    "['x1', 'y1']": [['r1', 'r2'], [73, 110]],
    "['x2', 'y2']": [['r2', 'r3'], [71, 103]]}
input1 = [['r1', 'r2'], [72, 112]]
mini=float('inf')
output = {}
for key, value in dict1.items():
    if value[0] == input1[0]:
        diff1 = abs(value[1][0] - input1[1][0])
        diff2 = abs(value[1][1] - input1[1][1])
        if diff1+diff2 < mini:
            output[key] = value
            mini=diff1+diff2
print(output)

Output:

{"['x1', 'y1']": [['r1', 'r2'], [73, 110]]}
Answered By: Yash Mehta
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.