将Python字典转换为列表 [英] Converting Python Dictionary to List

查看:1257
本文介绍了将Python字典转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何将Python字典转换为元组列表?

我正在尝试将Python字典转换为Python列表,以执行一些计算。

I'm trying to convert a Python dictionary into a Python list, in order to perform some calculations.

#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 = ""

这是我的尝试...但是我无法解决什么问题?

That's my attempt at it... but I can't work out what's wrong?

推荐答案

您的问题是您在引号中使用,即您正在设置 aKey 包含字符串key而不是变量的值 key 。此外,您不会清除 temp 列表,因此您每次都会添加它,而不是在其中添加两个项目。

Your problem is that you have key and value in quotes making them strings, i.e. you're setting aKey to contain the string "key" and not the value of the variable key. Also, you're not clearing out the temp list, so you're adding to it each time, instead of just having two items in it.

要修复您的代码,请尝试以下操作:

To fix your code, try something like:

for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

在使用它们之前,您不需要将循环变量复制到另一个变量中,所以我把它们丢了同样,您不需要使用追加来建立列表,您可以在方括号之间指定它,如上所示。如果我们想要尽可能简短,我们可以完成 dictlist.append([key,value])

You don't need to copy the loop variables key and value into another variable before using them so I dropped them out. Similarly, you don't need to use append to build up a list, you can just specify it between square brackets as shown above. And we could have done dictlist.append([key,value]) if we wanted to be as brief as possible.

或者只是按照建议使用 dict.items()

Or just use dict.items() as has been suggested.

这篇关于将Python字典转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆