开发者

how to convert list of dictonaries into ....?

li = [[{'foo': '1',
   'date': datetime.date(2011, 2, 1),
   'bar': 'a'},
  {'foo': '2',
   'date': datetime.date(2011, 2, 1),
   'bar': 'b'}],
 [{'foo': '2',
   'date': datetime.date(2011, 1, 30),
   'bar': 'f'},
  {'foo': '5',
   'date': datetime.date(2011, 1, 30),
   'bar': 'g'}]]

I want to convert this list into

     [{'date':datetime.date(2011, 2, 1), 
       'values':[{'foo': '1', 'bar': 'a'},{'foo':'2','bar': 'b'}]}, 
      {'date':datetime.date(2011, 1, 30), 
       'values':[{'foo': '2', 'bar开发者_运维问答':'f'},{'foo': '5','bar': 'g'}]}
     ]


Something like this?

dd = []
for l in li:
    d = {'date':l[0]['date'], 'values':[]}
    for ll in l:
        d['values'].append({'foo':ll['foo'], 'bar':ll['bar']})
    dd.append(d)



print dd

[{'date': datetime.date(2011, 2, 1),
  'values': [{'bar': 'a', 'foo': '1'}, {'bar': 'b', 'foo': '2'}]},
 {'date': datetime.date(2011, 1, 30),
  'values': [{'bar': 'f', 'foo': '2'}, {'bar': 'g', 'foo': '5'}]}]


I think the outer collection being a dict makes more sense:

from collections import defaultdict
from pprint import pprint

d = defaultdict(list)
for x in li:
    for y in x:
        d[y.pop('date')].append(y)

pprint(dict(d)) 

Which will produce:

{datetime.date(2011, 1, 30): [{'bar': 'f', 'foo': '2'},
                              {'bar': 'g', 'foo': '5'}],
 datetime.date(2011, 2, 1): [{'bar': 'a', 'foo': '1'},
                             {'bar': 'b', 'foo': '2'}]}

But if you want that list you can tack on:

L = []
for date, values in d.iteritems():
    L.append({'date':date, 'values':values})
pprint(L) 

Which gives:

[{'date': datetime.date(2011, 2, 1),
  'values': [{'bar': 'a', 'foo': '1'}, {'bar': 'b', 'foo': '2'}]},
 {'date': datetime.date(2011, 1, 30),
  'values': [{'bar': 'f', 'foo': '2'}, {'bar': 'g', 'foo': '5'}]}]


Another use of pop that reduces the size of the function:

>>> res = []
>>> for a_list in li:
    res_local = {'values': []}
    for d in a_list:
        res_local['date'] = d.pop('date')
        res_local['values'].append(d)
    res.append(res_local)


>>> res
[{'date': datetime.date(2011, 2, 1),
  'values': [{'foo': '1', 'bar': 'a'}, {'foo': '2', 'bar': 'b'}]},
 {'date': datetime.date(2011, 1, 30),
  'values': [{'foo': '2', 'bar': 'f'}, {'foo': '5', 'bar': 'g'}]}]

This solution has the advantage of being still valid if you have more items in your dicts than foo, date, bar, or if you remove some, etc: to sum it up, it will work if your dicts have at least a date entry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜