SQL_Roundabout
SQL_Roundabout

Reputation: 43

Comparing 2 dictionaries based on values for matching keys

I have 2 dictionaries:

S = {0: [1, 2, 3, 4], 
     1: [5, 6, 7, 8, 9, 10], 
     2: [11, 12, 13, 14, 15]}

R = {0: [1, 2, 8], 
    1: [8, 5, 10, 11, 15], 
    2: []}

I need to find out for a given key if any of the numbers in the list match. If they do then replace the numbers with 'X'.

The result should look like this

    F = {0: ['X', 'X', 3, 4], 
         1: ['X', 6, 7, 8, 9, 'X'], 
         2: [11, 12, 13, 14, 15]}
or 

F = [['X', 'X', 3, 4], ['X', 6, 7, 8, 9, 'X'], [11, 12, 13, 14, 15]]

I'm indifferent if F is a 3rd dictionary or a list of lists.

My code is as follows:

Solution = []

for x in S.values():
    for y in R.values():
        for j in y:
            for n, i in enumerate(x):
                if j == i:
                    x[n] = 'X'
                    
    Solution.append(x)  

The problem is that I'm comparing every value in R to each dictionary value in S. I'm not understanding how to compare for example [1, 2, 3, 4] to [1, 2, 8] independently of [5, 6, 7, 8, 9, 10] to [8, 5, 10, 11, 15].

Upvotes: 3

Views: 66

Answers (2)

dawg
dawg

Reputation: 103744

You can use sets:

# This modifies S in place; use a new dict if you want to keep S
for k,li1 in S.items():
    li2=R.get(k,[])
    diff=set(li1)-set(li2)
    S[k]=[e if e in diff else 'X' for e in li1] 


>>> S
{0: ['X', 'X', 3, 4], 1: ['X', 6, 7, 'X', 9, 'X'], 2: [11, 12, 13, 14, 15]}

With the set operation of difference - you can get what is in first list but not both:

>>> set([1,2,3,4]) - set([2,3,8])
{1, 4}

Once you know that, it is easy to change the list as desired.

If you want to have a list of lists, then you can use a comprehension:

LoL=[[e if e in set1 else 'X' for e in li1]
    for li1,set1 in 
        zip(S.values(), {k:set(li1)-set(R.get(k,[])) 
            for k,li1 in S.items()}.values())]

>>> LoL
[['X', 'X', 3, 4], ['X', 6, 7, 'X', 9, 'X'], [11, 12, 13, 14, 15]]

But IMHO the loop is easier to understand...

Upvotes: 5

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can use dictionary-comprehension:

F = {k: ["X" if vv in R.get(k, []) else vv for vv in v] for k, v in S.items()}
print(F)

Prints:

{0: ['X', 'X', 3, 4], 1: ['X', 6, 7, 'X', 9, 'X'], 2: [11, 12, 13, 14, 15]}

Upvotes: 3

Related Questions