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'}
Advertisement
Answer
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!