【问题标题】:Convert a list into a dictionary keeping the sequence intact将列表转换为字典,保持序列不变
【发布时间】:2015-09-17 16:46:36
【问题描述】:

我有一个很大的列表,想把它转换成这样的字典。 示例列表:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 输出字典:{'a':'b', 'c':'d', 'e':'f', 'g':'h'} 我希望序列是完整的。我读了另一篇类似的文章,它使用了来自 itertools 的 izip。我尝试将其用作:

from itertools import izip
i = iter(list_name)
dic = dict(izip(i, i))

但它给了我一本所有序列都混乱的字典。 此外,该列表具有偶数个元素。

【问题讨论】:

    标签: list python-2.7 dictionary type-conversion


    【解决方案1】:

    dicts无序的,您可以使用OrderedDict 来维护插入顺序:

    from collections import OrderedDict
    
    from itertools import izip
    i = iter(list_name)
    dic = OrderedDict(izip(i, i))
    

    输出:

    In [3]: list_name =  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']    
    In [4]: i = iter(list_name)   
    In [5]: dic = OrderedDict(izip(i, i))   
    In [6]: dic
    Out[6]: OrderedDict([('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2021-10-13
      • 2015-07-23
      • 1970-01-01
      • 2014-01-20
      • 2020-05-23
      • 2019-06-11
      相关资源
      最近更新 更多