stg*_*rge 0 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})
Run Code Online (Sandbox Code Playgroud)
这段代码工作得很好(虽然这不是我的解决方案).但是,如果我不想使用.keys()和.values()方法呢?在这种情况下,我尝试使用这样的东西,但我得到"unhashable type:'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})
Run Code Online (Sandbox Code Playgroud)
什么似乎是问题?
您正在尝试将整个keys列表用作键:
values.append(dict[keys])
Run Code Online (Sandbox Code Playgroud)
也许你打算用dict[key]呢?A list是一个可变类型,不能用作字典中的键(它可以就地更改,使得键不再可以在字典的内部哈希表中找到).
或者,循环遍历.items()序列:
for key, value in dct.items():
keys.append(key)
values.append(value)
Run Code Online (Sandbox Code Playgroud)
请不要dict用作变量名; 你这样做会影响内置类型.