Skip to main content
 首页 » 编程设计

python之自动将字典转换为字典列表

2025年05月04日7over140

将以下字典的 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}]