1👍
✅
works on python 2.6 +
use the dict constructor with enumerate.
list_of_dicts = [
{'completed__sum': 1, 'offer__count': 2, 'offer': 1},
{'completed__sum': 0, 'offer__count': 1, 'offer': 2}]
dictionary = dict((d['offer'], dict((k, v) for k, v in d.items() if k != 'offer')) for d in list_of_dicts)
print dictionary
>>>
{1: {'completed__sum': 1, 'offer__count': 2}, 2: {'completed__sum': 0, 'offer__count': 1}}
edit: just found a much better way to do this. if you arent using the list anymore and are going to keep only the final results.
dictionary = dict((d.pop('offer'), d) for d in list_of_dicts)
0👍
>>> {x['offer']: dict(y for y in x.iteritems() if y[0] != 'offer') for x in [{'completed__sum': 1, 'offer__count': 2, 'offer': 1}, {'completed__sum': 0, 'offer__count': 1, 'offer': 2}]}
{1: {'completed__sum': 1, 'offer__count': 2}, 2: {'completed__sum': 0, 'offer__count': 1}}
- [Answer]-Display max number of td elements in table row
- [Answer]-Django: getting error NoReverseMatch for reverse
- [Answer]-Django: Naive datetime on query
Source:stackexchange.com