几周前我开始学习 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()方法怎么办?在那种情况下,我尝试使用类似这样的东西,但我收到“不可散列的类型:'list'”错误消息:
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})
似乎是什么问题?