Skip to main content
 首页 » 编程设计

python之包含带有列表列表的键的字典

2025年05月04日10java哥

我有一个结构如下的字典:

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

有人能给我指明正确的方向,以便遍历原始字典来创建新字典吗?

请您参考如下方法:

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