如果我有一本像这样的字典:

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

我怎么把它转换成这个?

[('a', 1), ('b', 2), ('c', 3)]

我怎么把它转化成这个?

[(1, 'a'), (2, 'b'), (3, 'c')]

当前回答

你需要的是dict的items()和iteritems()方法。Items返回一个(键,值)元组列表。因为元组是不可变的,所以它们不能被反转。因此,您必须迭代这些项并创建新的元组以获得反向的(value,key)元组。对于迭代,iteritems更可取,因为它使用生成器生成(key,value)元组,而不必将整个列表保存在内存中。

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 

其他回答

因为没有人这样做,我将添加py3k版本:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]

你需要的是dict的items()和iteritems()方法。Items返回一个(键,值)元组列表。因为元组是不可变的,所以它们不能被反转。因此,您必须迭代这些项并创建新的元组以获得反向的(value,key)元组。对于迭代,iteritems更可取,因为它使用生成器生成(key,value)元组,而不必将整个列表保存在内存中。

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>> 
[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]

另一个选择是

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (value, key) tuples

这些是Python 3的重大变化。Python 2.x

Python3。x使用

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

对于Python 2.7使用

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)