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

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

我怎么把它转换成这个?

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

我怎么把它转化成这个?

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

当前回答

因为没有人这样做,我将添加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')]

其他回答

另一个选择是

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

通过dictionary和zip的keys()和values()方法。

Zip将返回一个元组列表,它的作用类似于一个有序字典。

演示:

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

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

在Python 2中,你不需要list。

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

and

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