For my script, I need to check if some object is a list of dictionnaries or a list of list of dictionnaries in order to perform corresponding actions, or else raise an error.
To be more specific, the following should be accepted (with two different conditions):
mylist = [{'a': 1, 'b': 2}, {'c': 3},{'d': 4}]
mylist1 = [[{'a':1}, {'ccc':4}], [{'e': 3}]]
but, for instance, the following should raise an error:
c = [[]]
d = [[{'a':1}], {'b':2}]
I have implemented a naive solution as follows:
if set([type(x) for x in mylist]) == set([dict]):
print('first case')
elif set([type(x) for x in mylist]) == set([list]) and set([type(x) for y in mylist for x in y ])== set([dict]):
print('second case')
else:
raise Exception('wrong structure')
I tried using a schema validation but I do not seem to get how to do that. Any help to make this more readable / elegant would be appreciated!!
Thanking you in advance,
M