Testing for equality works fine like this for python dicts:
first = {"one":"un", "two":"deux", "three":"trois"}
second = {"one":"un", "two":"deux", "three":"trois"}
print(first == second) # Result: True
But now my second dict contains some additional keys I want to ignore:
first = {"one":"un", "two":"deux", "three":"trois"}
second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"}
Is there a simple way to test if the first dict is part of the second dict, with all its keys and values?
EDIT 1:
This question is suspected to be a duplicate of How to test if a dictionary contains certain keys, but I'm interested in testing keys and their values. Just containing the same keys does not make two dicts equal.
EDIT 2:
OK, I got some answers now using four different methods, and proved all of them working. As I need a fast process, I tested each for execution time. I created three identical dicts with 1000 items, keys and values were random strings of length 10. The second
and third
got some extra key-value pairs, and the last non-extra key of the third
got a new value. So, first
is a subset of second
, but not of third
. Using module timeit
with 10000 repetitions, I got:
Method Time [s]
first.viewitems() <=second.viewitems() 0.9
set(first.items()).issubset(second.items()) 7.3
len(set(first.items()) & set(second.items())) == len(first) 8.5
all(first[key] == second.get(key, sentinel) for key in first) 6.0
I guessed the last method is the slowest, but it's on place 2. But method 1 beats them all.
Thanks for your answers!