[英]auto convert dictionary into list of dictionaries
将以下字典的filter [X] ...键/值自动转换为(嵌套的)词典列表的最简单方法是什么。
{'filter[0][data][type]': u'string',
'filter[0][data][value]': u'T',
'filter[0][field]': u'company',
'filter[1][data][comparison]': u'lt',
'filter[1][data][type]': u'numeric',
'filter[1][data][value]': u'100',
'filter[1][field]': u'price',
'filter[2][data][comparison]': u'gt',
'filter[2][data][type]': u'numeric',
'filter[2][data][value]': u'10',
'filter[2][field]': u'price',
'limit': u'10',
'page': u'1',
'sort': u'[{"property":"company","direction":"ASC"}]',
'start': u'0'}
我想要的结果看起来像:
[
{'data': {'type': 'string', 'value': 'T'}, 'field': 'company'},
{'data': {'comparison': 'lt', 'type': 'numeric', 'value': 100},
'field': 'price'},
{'data': {'comparison': 'gt', 'type': 'numeric', 'value': 10},
'field': 'price'}
]
最初的字典来自extjs网格过滤器插件GET请求传递的Pylons
extjs网格过滤器中还有一个选项可以对过滤器json进行编码,因此我最终得到了:
{ 'filter': u'[{"type":"string","value":"T","field":"company"},{"type":"numeric","comparison":"lt","value":100,"field":"price"},{"type":"numeric","comparison":"gt","value":10,"field":"price"}]',
'limit': u'10',
'page': u'1',
'sort': u'[{"property":"company","direction":"ASC"}]',
'start': u'0'}
但是我仍然不知道如何将这种自动转换为python列表和字典。
我事先不知道查询的过滤器数量,因此使用创建的字典列表,我可以遍历该列表并自动生成sql查询。 (尽管也许有更好的方法可以做到这一点?)
找到了解决方案:以json编码的形式通过过滤器,然后只需要使用json.loads()即可得到字典列表。
>>> import json
>>> dict = {'filter': u'[{"type":"string","value":"T","field":"company"},{"type":"numeric","comparison":"lt","value":100,"field":"price"},{"type":"numeric","comparison":"gt","value":10,"field":"price"}]',
'limit': u'10',
'page': u'1',
'sort': u'[{"property":"company","direction":"ASC"}]',
'start': u'0'}
>>> json.loads(dict['filter'])
[{u'field': u'company', u'type': u'string', u'value': u'T'},
{u'comparison': u'lt',
u'field': u'price',
u'type': u'numeric',
u'value': 100},
{u'comparison': u'gt', u'field': u'price', u'type': u'numeric', u'value': 10}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.