【问题标题】:Dict containing keys with lists of lists包含带有列表列表的键的字典
【发布时间】:2013-04-04 19:01:28
【问题描述】:

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

{ '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] 成为新 dict 中的键,而 ['records'] 中每个列表的其余部分成为该键的值。

这样的事情是我的想法,甚至可能不可能,我是 Python 新手:

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

有人可以指出我正确的方向来遍历原始字典以创建新字典吗?

【问题讨论】:

  • 您希望值是list,还是列表的字符串表示形式?
  • 请指定正确的输出,这是无效的:'['2013-04-02','Italy','meh','heh',3,4]
  • 我很确定是一个列表,我想要访问这些列表的内容及其索引。我也修复了输出,对此感到抱歉。

标签: python


【解决方案1】:

如果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】:
    rec_lsts = orgi_dict['records']
    new_dict = {}
    for l_list in rec_lsts:
        new_dict[l_lst[0]] = l_lst[1:]
    

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-23
        • 1970-01-01
        相关资源
        最近更新 更多