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?
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.
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.
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.
commons = set(dict1).intersection(set(dict2))
list1 = [dict1[k] for k in commons]
list2 = [dict2[k] for k in commons]
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]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With