我将两个列表组合成一个字典。现在我想返回与特定年龄相关的所有名称。当我在下面运行时,我收到下面输出中显示的错误。如何在函数“people”中的第一个函数中使用字典
names = ['Katie', 'Bill', 'Cate', 'David', 'Erwin', 'Franz', 'Rich', 'Heath', 'Ivan', 'Justin', 'Kelly', 'Lauren']
ages = [17, 21, 17, 17, 19, 21, 20, 20, 19, 19, 22, 19]
def combine_lists_into_dict():
dictionary = dict(zip(names,ages))
return dictionary
print combine_lists_into_dict()
def people(ages):
dictionary.get(ages, default = None)
return names
print people('20')
输出:
{'Lauren': 19, 'Justin': 19, 'Kelly': 22, 'Cate': 17, 'Bill': 21, 'David': 17, 'Erwin': 19, 'Ivan': 19, 'Rich': 20, 'Franz': 21, 'Heath': 20, 'Katie': 17}
Traceback (most recent call last):
line 50, in <module>
print people('20')
line 48, in people
dictionary.get(ages, default = None)
NameError: global name 'dictionary' is not defined
最佳答案
三个问题:
dictionary
是一个局部变量,因此people
函数看不到它,因此未定义全局名称“dictionary”
。.get()
按键查找,而不是按值查找,因此它不会返回您想要的内容。- 当年龄为整数时,传递字符串
'20'
来表示年龄。
要解决问题 #1,请将从 combine_lists_into_dict
返回的字典分配给一个变量,并将该变量传递给需要它的函数。
要解决问题 #2,请使用列表推导式返回与年龄匹配的名称。
对于#3,传递一个整数。
names = ['Katie', 'Bill', 'Cate', 'David', 'Erwin', 'Franz', 'Rich', 'Heath', 'Ivan', 'Justin', 'Kelly', 'Lauren']
ages = [17, 21, 17, 17, 19, 21, 20, 20, 19, 19, 22, 19]
def combine_lists_into_dict():
dictionary = dict(zip(names,ages))
return dictionary
def people(D,age):
return [key for key,value in D.items() if value == age]
D = combine_lists_into_dict()
print people(D,20)
输出:
['Rich', 'Heath']
关于Python从字典中检索所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867477/