如何将字典转换为元组列表? [英] How can I convert a dictionary into a list of tuples?
本文介绍了如何将字典转换为元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的字典:
{ 'a': 1, 'b': 2, 'c': 3 }
如何将其转换为此?
[ ('a', 1), ('b', 2), ('c', 3) ]
如何将其转换为此?
[ (1, 'a'), (2, 'b'), (3, 'c') ]
推荐答案
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> d.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
它不是您想要的顺序,但是字典没有任何特定的顺序. 1 对其进行排序或根据需要进行组织.
It's not in the order you want, but dicts don't have any specific order anyway.1 Sort it or organize it as necessary.
请参阅: items(),在Python 3.x中,您将不使用iteritems
(不再存在),而使用items
,现在它返回词典项目的视图".请参见新功能文档(适用于Python 3.0)和新的视图文档.
In Python 3.x, you would not use iteritems
(which no longer exists), but instead use items
, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views.
1:字典的插入顺序保留为在Python 3.7中添加
这篇关于如何将字典转换为元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文