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

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

问题描述

我正在尝试将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?

推荐答案

您的问题是您在引号中使用keyvalue使其成为字符串,即您要设置aKey包含字符串,而不是变量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)

在使用它们之前,您不需要将循环变量keyvalue复制到另一个变量中,因此我将其删除.同样,您无需使用append即可建立列表,只需在方括号之间指定它即可,如上所示.如果我们想尽可能简短,我们可以做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().

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

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