【问题标题】:From a list of lists to a dictionary从列表列表到字典
【发布时间】:2013-02-20 17:31:44
【问题描述】:

我有一个结构非常具体的列表,如下所示:

lol = [['geo','DS_11',45.3,90.1,10.2],['geo','DS_12',5.3,0.1,0.2],['mao','DS_14',12.3,90.1,1],...]

我想将此 lol(列表列表)转换为以下形式的字典(请注意,lol 中每个列表的第二个元素应该是唯一的,因此是我的 dict 的一个好键:

dict_lol = {'DS_11': ['geo','DS_11',45.3,90.1,10.2], 'DS_12':['geo','DS_12',5.3,0.1,0.2], 'DS_14':['mao','DS_14',12.3,90.1,1],...}

我可以做一个 for 循环,但我正在寻找一种更优雅的 Python 方式来做它。

谢谢!

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    使用字典理解,在 python 2.7+ 中可用

    In [93]: {x[1]:x for x in lol}
    Out[93]: 
    {'DS_11': ['geo', 'DS_11', 45.3, 90.1, 10.2],
     'DS_12': ['geo', 'DS_12', 5.3, 0.1, 0.2],
     'DS_14': ['mao', 'DS_14', 12.3, 90.1, 1]}
    

    【讨论】:

      【解决方案2】:

      我相信这是最 Pythonic 的解决方案,使用 dictionary comprehensions:

      dict_lol = {item[1]: item for item in lol}
      

      如果它不可用(例如在 Python

      dict_lol = dict((item[1], item) for item in lol)
      

      【讨论】:

        【解决方案3】:

        像这样:

        {l[1]:l for l in lol}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-17
          • 1970-01-01
          • 2021-03-17
          • 1970-01-01
          • 2019-05-02
          相关资源
          最近更新 更多