如果我有一本像这样的字典:
{'a': 1, 'b': 2, 'c': 3}
我怎么把它转换成这个?
[('a', 1), ('b', 2), ('c', 3)]
我怎么把它转化成这个?
[(1, 'a'), (2, 'b'), (3, 'c')]
如果我有一本像这样的字典:
{'a': 1, 'b': 2, 'c': 3}
我怎么把它转换成这个?
[('a', 1), ('b', 2), ('c', 3)]
我怎么把它转化成这个?
[(1, 'a'), (2, 'b'), (3, 'c')]
当前回答
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
k = (i,d[i])
list.append(k)
print list
其他回答
这些是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)
>>> 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')]
您可以使用列表推导式。
[(k,v) for k,v in a.iteritems()]
会得到[('a', 1), ('b', 2), ('c', 3)]和
[(v,k) for k,v in a.iteritems()]
另一个例子。
如果你喜欢,可以阅读更多关于列表推导式的内容,你可以用它们做什么是非常有趣的。
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中获取输入,并使用元组的第一个值进行排序
另一个选择是
list(dictionary.items()) # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys())) # list of (value, key) tuples