【问题标题】:python : use elements from a list as keys to a dictionary in order of list [duplicate]python:按列表顺序使用列表中的元素作为字典的键[重复]
【发布时间】:2013-11-25 09:41:44
【问题描述】:
my_lst = ['b','c','a']
dict = {}
for i in my_lst[]:
    dict[i] = []
print dict
# prints: => {'c': [], 'b': [], 'a': []}

我怎样才能让 dict 成为{'b': [ ], 'c': [ ], 'a': [ ]} 键的顺序与列表中的顺序相似吗?

【问题讨论】:

    标签: python list sorting dictionary


    【解决方案1】:

    您正在寻找OrderedDict

    >>> from collections import OrderedDict
    >>> my_lst = ['b','c','a']
    >>> D = OrderedDict()
    >>> for i in my_lst:
    ...     D[i] = []
    >>> D
    OrderedDict([('b', []), ('c', []), ('a', [])])
    >>> print D.items()
    [('b', []), ('c', []), ('a', [])]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 2021-08-21
      • 2018-10-22
      • 2015-04-07
      • 2023-03-27
      • 2015-09-13
      • 2016-05-28
      • 1970-01-01
      相关资源
      最近更新 更多