The order of keys in dictionaries

前端 未结 6 989
渐次进展
渐次进展 2020-11-22 14:32

Code:

d = {\'a\': 0, \'b\': 1, \'c\': 2}
l = d.keys()

print l

This prints [\'a\', \'c\', \'b\']. I\'m unsure of how the metho

6条回答
  •  无人共我
    2020-11-22 14:48

    You could use OrderedDict (requires Python 2.7) or higher.

    Also, note that OrderedDict({'a': 1, 'b':2, 'c':3}) won't work since the dict you create with {...} has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)]).

    As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.

提交回复
热议问题