【问题标题】:create dictionary from list - in sequence从列表创建字典 - 按顺序
【发布时间】:2013-08-24 09:48:48
【问题描述】:

我想从列表中创建字典

>>> list=['a',1,'b',2,'c',3,'d',4]
>>> print list
['a', 1, 'b', 2, 'c', 3, 'd', 4]

我使用 dict() 从列表中生成字典 但结果并没有按预期顺序排列。

>>> d = dict(list[i:i+2] for i in range(0, len(list),2))
>>> print d
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

我希望结果按照列表的顺序排列。

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

请大家帮忙指点一下好吗?

【问题讨论】:

  • 字典中的键没有排序。你为什么期待这个订单?因为它与列表中的相同还是因为它是字典式的?也许你不需要字典。您能否添加更多关于您将如何使用“d”的信息?

标签: python list dictionary


【解决方案1】:

字典没有任何顺序,如果您希望保留顺序,请使用collections.OrderedDict。而不是使用索引,而是使用iterator

>>> from collections import OrderedDict
>>> lis = ['a', 1, 'b', 2, 'c', 3, 'd', 4]
>>> it = iter(lis)
>>> OrderedDict((k, next(it)) for k in it)
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])

【讨论】:

    【解决方案2】:

    字典是一种无序的数据结构。要保留订单,请使用collection.OrderedDict:

    >>> lst = ['a',1,'b',2,'c',3,'d',4]
    >>> from collections import OrderedDict
    >>> OrderedDict(lst[i:i+2] for i in range(0, len(lst),2))
    OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    

    【讨论】:

      【解决方案3】:

      您可以使用grouper recipe:zip(*[iterable]*n) 将项目收集到n 的组中:

      In [5]: items = ['a',1,'b',2,'c',3,'d',4]
      
      In [6]: items = iter(items)
      
      In [7]: dict(zip(*[items]*2))
      Out[7]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
      

      附言。永远不要将变量命名为 list,因为它会隐藏同名的内置函数(类型)。

      石斑鱼食谱好用,不过a little harder to explain

      dict 中的项目是无序的。因此,如果您希望 dict 项按特定顺序排列,请使用 collections.OrderedDict(正如 falsetru 已经指出的那样):

      In [13]: collections.OrderedDict(zip(*[items]*2))
      Out[13]: OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
      

      【讨论】:

      • 我只是注意到items = iter(items) 可能会导致一些微妙的问题,如果items 预计以后会被用作列表...
      猜你喜欢
      • 1970-01-01
      • 2019-10-20
      • 2021-07-03
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多