nandi1596
nandi1596

Reputation: 69

How to compare two dictionaries with list values?

Two dictionaries i'm using have the same key. They have lists as value. So example

    a={'Q':[0, 0, 0], 'T'=[6, 0, 0, 0]......}
    b={'Q':[0, 0], 'T'=[0, 6, 0, 0]........}

I have to check how many values match out of the two. I did this

    def shared_keyvals(dict1, dict2):
        return dict( (key, dict1[key])
             for key in (set(dict1) & set(dict2))
             if dict1[key] == dict2[key]
           )

but it does not compare T=[6,0,0,0] same as T=[0,6,0,0].

So ultimately I want to calculate the no.values b got same as a. So for this example no.of values same of a and b would be 6 (out of 7)

Upvotes: 1

Views: 301

Answers (1)

Kraigolas
Kraigolas

Reputation: 5560

This works:

def compare(a, b):
    """Compare two lists and add up the number of matching elements."""
    a.sort()
    b.sort()
    if len(a) > len(b): # make a the shorter list 
        a, b = b, a 
    count = 0 
    for i in range(len(a)):
        if a[i] == b[i]:
            count += 1 
    return count 


a={'Q':[0, 0, 0], 'T':[6,0,0,0]}
b={'Q':[0, 0], 'T':[0, 6, 0, 0]}

dictionary = {key : compare(a[key], b[key]) for key in a.keys()}
# {'Q': 2, 'T': 4}

Upvotes: 3

Related Questions