Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert a dict contains another dict without assertDictContainsSubset in python? [duplicate]

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

like image 640
JerryCai Avatar asked Jan 11 '14 03:01

JerryCai


People also ask

Can a Python dictionary contain another dictionary?

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.

Can a dict contain a dict?

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.

How do you check if a dict contains a key?

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.

Can dict have different data types?

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.


2 Answers

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.

like image 62
kepler Avatar answered Oct 05 '22 01:10

kepler


>>> 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.

like image 27
John1024 Avatar answered Oct 05 '22 01:10

John1024