2013-04-04 47 views
1

列表含有键我有一个字典结构如下:字典使用列表

{ '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创建json.load。

如何迭代记录键以使['records'] [0]成为新词典中的键并且['records']中每个列表的其余部分都是该键的值。

像这样的东西是什么,我想,可能甚至是不可能的,我是新来的Python:

{ '15':['2013-04-02','Mexico','blah','bleh',1,2], '25':['2013-04-02','Italy','meh','heh',3,4] } 

有人能指出我在正确的方向去约通过原字典迭代创建新的那一个?

+1

你想要的值是一个'list',或列表的字符串表示? – tacaswell 2013-04-04 19:03:16

+0

请指定一个正确的输出,这是无效的:''['2013-04-02','意大利','meh','heh',3,4]' – 2013-04-04 19:12:48

+0

我非常确定一个列表,我要去想要使用索引访问这些列表的内容。我也修正了输出,对此很抱歉。 – 2013-04-04 19:13:27

回答

1
rec_lsts = orgi_dict['records'] 
new_dict = {} 
for l_list in rec_lsts: 
    new_dict[l_lst[0]] = l_lst[1:] 
+0

谢谢,这个工程。 – 2013-04-04 19:15:32

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

为什么downvote? – NPE 2013-04-04 19:09:22