字典转换为列表?
我想把一个Python字典转换成一个Python列表,这样我就可以进行一些计算。
#My dictionary
dict = {}
dict['Capital']="London"
dict['Food']="Fish&Chips"
dict['2012']="Olympics"
#lists
temp = []
dictList = []
#My attempt:
for key, value in dict.iteritems():
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
aKey = ""
aValue = ""
这是我尝试的代码……但我不知道哪里出错了?
7 个回答
279
在Python中,将字典(dict)转换成列表非常简单。这里有三个例子:
>> d = {'a': 'Arthur', 'b': 'Belling'}
>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]
>> d.keys()
['a', 'b']
>> d.values()
['Arthur', 'Belling']
557
dict.items()
这个方法有效。
(仅适用于Python 2)
185
你的问题在于,你把 key
和 value
用引号包起来了,这样它们就变成了字符串。也就是说,你把 aKey
设置成了字符串 "key"
,而不是变量 key
的值。此外,你没有清空 temp
列表,所以每次都在往里面添加内容,而不是只保留两个项目。
要修复你的代码,可以试试下面的方式:
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
你不需要在使用 key
和 value
之前把它们复制到另一个变量,所以我把这部分去掉了。同样,你也不需要用 append
来构建列表,你可以直接在方括号中指定它们,就像上面那样。如果想要简洁一点,我们也可以用 dictlist.append([key,value])
。
或者直接使用 dict.items()
,正如之前提到的那样。