您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中,如何按已排序的键顺序遍历字典?

在Python中,如何按已排序的键顺序遍历字典?

尚未对此进行广泛的测试,但是可以在Python 2.5.2中使用。

>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>

如果您习惯于使用for key, value in d.iteritems(): ...迭代器代替迭代器,那么上面的解决方案仍然可以使用

>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>

在Python 3.x中,使用d.items()代替d.iteritems()返回迭代器。

python 2022/1/1 18:32:44 有210人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶