Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Estimated output I want:

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

>Solution :

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]]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading