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

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

我怎么把它转换成这个?

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

我怎么把它转化成这个?

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

当前回答

x = {'a': 1, 'b': 2, 'c': 4, 'd':3}   
sorted(map(lambda x : (x[1],x[0]),x.items()),key=lambda x : x[0])

让我们把上面的代码分解成几个步骤

step1 = map(lambda x : (x[1],x[0]),x.items())

x[1]:值 x[0]:键

Step1将创建一个元组列表,其中包含(value,key)形式的对,例如(4,'c')

step2 = sorted(step1,key=lambda x : x[0]) 

Step2从步骤1中获取输入,并使用元组的第一个值进行排序

其他回答

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

这些是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)
>>> 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()]
>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]