简体   繁体   中英

auto convert dictionary into list of dictionaries

What would be the easiest way to automatic convert the filter[X]... keys/values of the following dictionary to a list of (nested) dictionaries.

{'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'}

The result I want would look like:

[
  {'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'}
]

The initial dictonary is from Pylons passed from an extjs grid filter plugin GET request

There is also an option in extjs grid filter to have the filter json encoded so I end up with:

{ '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'}

But again I have not idea how to convert this automatic to python list and dict.

I do not know beforehand the amount of filters for the query so with the created list of dictionaries I can loop over the list and automatic generate an sql query. (though maybe there is a better way to do this?)

Found the solution: pass the filter as json encoded and then is just a matter of using json.loads() and I get a list of dictionaries.

>>> 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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM