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

{'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 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]

对于Python 3.6及更高版本,列表的顺序是您所期望的。

在Python 2中,你不需要list。

其他回答

你需要的是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')]

Python3 dict.values()不返回列表。这是一个例子

mydict = {
  "a": {"a1": 1, "a2": 2},
  "b": {"b1": 11, "b2": 22}
}

print(mydict.values())
> output: dict_values([{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}])

print(type(mydict.values()))
> output: <class 'dict_values'>

print(list(mydict.values()))
> output: [{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}]

print(type(list(mydict.values())))
> output: <class 'list'>

另一个选择是

list(dictionary.items())  # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys()))  # list of (value, key) tuples
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]

对于Python 3.6及更高版本,列表的顺序是您所期望的。

在Python 2中,你不需要list。