Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two large dictionaries and create lists of values for keys they have in common

Tags:

I have a two dictionaries like:

dict1 = { (1,2) : 2, (2,3): 3, (1,3): 3}
dict2 = { (1,2) : 1, (1,3): 2}

What I want as output is two list of values for the items which exist in both dictionaries:

[2,3]
[1,2]

What I am doing right now is something like this:

list1 = []
list2 = []

for key in dict1.keys():
    if key in dict2.keys():
        list1.append(dict1.get(key))
        list2.append(dict2.get(key))

This code is taking too long running which is not something that I am looking forward to. I was wondering if there might be a more efficient way of doing it?

like image 944
ahajib Avatar asked Apr 14 '16 16:04

ahajib


People also ask

How do you compare keys in two dictionaries?

Python List cmp() Method. The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

What are the similarities and differences between list and dictionary?

Similarity: Both List and Dictionary are mutable datatypes. Dissimilarity: List is a sequential data type i.e. they are indexed. Dictionary is a mapping datatype.

Can you compare two dictionaries in Python?

You can use the == operator, and it will work. However, when you have specific needs, things become harder. The reason is, Python has no built-in feature allowing us to: compare two dictionaries and check how many pairs are equal.


2 Answers

commons = set(dict1).intersection(set(dict2))
list1 = [dict1[k] for k in commons]
list2 = [dict2[k] for k in commons]
like image 166
BlackBear Avatar answered Sep 29 '22 12:09

BlackBear


Don't use dict.keys. On python2.x, it creates a new list every time it is called (which is an O(N) operation -- And list.__contains__ is another O(N) operation on average). Just rely on the fact that dictionaries are iterable containers directly (with O(1) lookup):

list1 = []
list2 = []

for key in dict1:
    if key in dict2:
        list1.append(dict1.get(key))
        list2.append(dict2.get(key))

Note that on python2.7, you can use viewkeys to get the intersection directly:

>>> a = {'foo': 'bar', 'baz': 'qux'}
>>> b = {'foo': 'bar'}
>>> a.viewkeys() & b
set(['foo'])

(on python3.x, you can use keys here instead of viewkeys)

for key in dict1.viewkeys() & dict2:
    list1.append(dict1[key]))
    list2.append(dict2[key]))
like image 33
mgilson Avatar answered Sep 29 '22 13:09

mgilson