如果我有一本像这样的字典:
{'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')]
当前回答
这些是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)
其他回答
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'>
这些是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)
[(k,v) for (k,v) in d.iteritems()]
and
[(v,k) for (k,v) in d.iteritems()]
你需要的是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')]
>>>
通过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')]