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

Finding any changes between two lists of the same length

Given 2 lists of the same length. Is it possible to return a dict containing any changes between the 2 lists. Each key being the value that was changed and the key’s value being the value it was changed to. The following returns difference between the 2 lists:

differences = (first_set - sec_set).union(sec_set - first_set)

I am looking to go one step further and save the results as a dict. Here is an example of what I am looking for:

first_set = [1, 4, 6, 8, 9]
sec_set = [1, 4, 5, 4, 9]

Output:

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

dict = {'6':'5', '8':'4'}

>Solution :

Lots of ways to do this, if you’d like an expanded answer this should do it. Just looping through the first list and using total to keep track of the index, and then checking that index on the second list. Then chucking them into a dict when they don’t match.

first_set = [1, 4, 6, 8, 9]
sec_set   = [1, 4, 5, 4, 9]
mis_dict = {}

total = 0
for one in first_set:
    if one != sec_set[total]:
        mis_dict[one] = sec_set[total]
    total += 1

print(mis_dict)

Output:

{6: 5, 8: 4}

You can certainly one line this as well, or anything in between. Just depends on what works best for you!

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