Home > Back-end >  Finding any changes between two lists of the same length
Finding any changes between two lists of the same length

Time:07-08

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:

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

CodePudding user response:

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!

CodePudding user response:

You can just go through the loop, checking if the elements are different, and if they are different write to the dictionary:

for i in range(len(first)):
    if first[i] != second[i]:
        dct[str(first[i])] = str(second[i])
print(dct)

CodePudding user response:

You can combine a generator expression with zip in the standard dict constructor:

dict((a, b) for a, b in zip(first, second) if a != b)

CodePudding user response:

You can use a dict comprehension:

out = {a: b for a, b in zip(first_set, sec_set) if a != b}
print(out)

# Output
{6: 5, 8: 4}

With module itertools:

from itertools import filterfalse

out = dict(filterfalse(lambda x: x[0] == x[1], zip(first_set, sec_set)))
print(out)

# Output
{6: 5, 8: 4}
  • Related