我的dict结构如下:
{ 'records':[['15','2013-04-02','Mexico','blah','bleh',1,2],['25','2013-04-02','Italy','meh','heh',3,4]], 'attributes':['id','date','location','descr1','descr2','total1','total2'] }
它是使用json.load从json创建的。
如何迭代记录键,使['records'] [0]成为新词典中的一个键,['records']中每个列表的其余部分为该键的值。
像我这样的东西,甚至可能是不可能的,我是Python的新手:
{ '15':['2013-04-02','Mexico','blah','bleh',1,2], '25':['2013-04-02','Italy','meh','heh',3,4] }
有人能指出我正确的方向来迭代原始的dict来创建新的dict吗?
答案 0 :(得分:7)
如果d
是您的字典:
In [5]: {rec[0]:rec[1:] for rec in d['records']}
Out[5]:
{'15': ['2013-04-02', 'Mexico', 'blah', 'bleh', 1, 2],
'25': ['2013-04-02', 'Italy', 'meh', 'heh', 3, 4]}
答案 1 :(得分:1)
rec_lsts = orgi_dict['records']
new_dict = {}
for l_list in rec_lsts:
new_dict[l_lst[0]] = l_lst[1:]
答案 2 :(得分:0)
d = { 'records':[['15','2013-04-02','Mexico','blah','bleh',1,2], ['25','2013-04-02','Italy','meh','heh',3,4]], 'attributes':['id','date','location','descr1','descr2','total1','total2']}
new_d = {}
for a in d['records']:
new_d[a[0]] = a[1:]
print new_d