I know assertDictContainsSubset
can do this in python 2.7, but for some reason it's deprecated in python 3.2. So is there any way to assert a dict contains another one without assertDictContainsSubset
?
This seems not good:
for item in dic2: self.assertIn(item, dic)
any other good way? Thanks
A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, 'courses' is a nested dictionary that contains other dictionary of three elements in each key.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type. Nested Dictionary: Nesting Dictionary means putting a dictionary inside another dictionary.
Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
Although I'm using pytest, I found the following idea in a comment. It worked really great for me, so I thought it could be useful here:
assert dict1.items() <= dict2.items()
for Python 3 and
assert dict1.viewitems() <= dict2.viewitems()
for Python 2.
It works with non-hashable items, but you can't know exactly which item eventually fails.
>>> d1 = dict(a=1, b=2, c=3, d=4) >>> d2 = dict(a=1, b=2) >>> set(d2.items()).issubset( set(d1.items()) ) True
And the other way around:
>>> set(d1.items()).issubset( set(d2.items()) ) False
Limitation: the dictionary values have to be hashable.
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