Python错误:不可用类型:'list'

时间:2013-05-28 23:58:03

标签: python dictionary tuples

几周前我开始学习Python(以前没有它的知识也没有编程)。 我想创建一个定义,它将给定字典作为参数返回一个由两个列表组成的元组 - 一个只有字典的键,另一个只有给定字典的值。 基本上代码看起来像这样:

"""Iterate over the dictionary named letters, and populate the two lists so that 
keys contains all the keys of the dictionary, and values contains 
all the corresponding values of the dictionary. Return this as a tuple in the end."""

def run(dict):
    keys = []
    values = []
    for key in dict.keys():
        keys.append(key)
    for value in dict.values():
        values.append(value)
    return (keys, values)


print run({"a": 1, "b": 2, "c": 3, "d": 4})

这段代码完美无缺(虽然这不是我的解决方案)。 但是如果我不想使用 .keys() .values()方法呢? 在这种情况下,我尝试使用这样的东西,但我得到“不可用的类型:'列表'”错误消息:

def run(dict):
    keys = []
    values = []
    for key in dict:
        keys.append(key)
        values.append(dict[keys])
    return (keys, values)


print run({"a": 1, "b": 2, "c": 3, "d": 4})

什么似乎是问题?

3 个答案:

答案 0 :(得分:6)

您正尝试将整个keys列表用作关键字:

values.append(dict[keys])

也许您打算使用dict[key]代替? list是一个可变类型,不能用作字典中的键(它可以就地更改,使得键不再可以在字典的内部哈希表中找到)。

或者,循环遍历.items()序列:

for key, value in dct.items():
    keys.append(key)
    values.append(value)

请不要将dict用作变量名称;你这样做会影响内置类型。

答案 1 :(得分:3)

编写函数的另一种更简单(错误的机会)

def run(my_dict):
    return zip(*my_dict.items())

答案 2 :(得分:2)

Martijn的回答是正确的,但也要注意你的原始样本做的工作比它需要的多。 dict.keys()和dict.values()都返回列表,没有理由重新创建它们。代码可以是:

def run(my_dict):
    return my_dict.keys(), my_dict.values()

print run({"a": 1, "b": 2, "c": 3, "d": 4})