我对Python相当陌生,我试图将过滤器查询建立为带有n深度字典的最终结果。里面可以有其他字典和列表。如何遍历一个深度嵌套的字典,其中包含Python中的列表和其他字典?
这是我的结构:
filters = {
predicate: 'AND',
filters: [
{'property_class_id': 10, operator: 'contains', operands: ['FOO']},
{
predicate: 'NOT',
filters: [{
predicate: 'OR',
filters: [
{'property_class_id': 1, operator: 'contains', operands: ['Hello']},
{'property_class_id': 2, operator: 'contains', operands: ['my search term']}
]
}]
},
{
predicate: 'OR',
filters: [
{'property_class_id': 3, operator: 'contains', operands: ['my search term']},
{'property_class_id': 4, operator: 'contains', operands: ['my search term']}
]
}
]
}
我希望这将转化为A +符合Q对象(B或C)+(d或E)!
然而,我的第一个问题是,如何遍历每个键值对的字典?
这是我迄今为止的内容,但您可以在列表中找到限制,因为for循环只接受字典。
def unpack_filter(self, filters):
q_object = Q()
q_list = []
for key, value in filters.iteritems():
if isinstance(value, list) or isinstance(value, dict):
self.unpack_filter(value)
else:
print "{0} : {1}".format(key, value)