Python从字典中检索所有项目

标签 python list dictionary

我将两个列表组合成一个字典。现在我想返回与特定年龄相关的所有名称。当我在下面运行时,我收到下面输出中显示的错误。如何在函数“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

最佳答案

三个问题:

  1. dictionary 是一个局部变量,因此 people 函数看不到它,因此未定义全局名称“dictionary”
  2. .get() 按键查找,而不是按值查找,因此它不会返回您想要的内容。
  3. 当年龄为整数时,传递字符串 '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/

相关文章:

python - Pandas /Python : 2D histogram fails with value error

Java:按照另一个列表中对象的顺序迭代一个列表

python - 计算列表 Python 中有多少个对象类型

haskell - 让 Data.Map 成为 Haskell 中的仿函数

python - 使用 matplotlib 在一个循环内的两个独立图形窗口中的子图

python - Model.objects.filter([外部表]).update()

python - 使用 python 编写 Ev3 窗口代码

python - 根据Python中另一个数组上的重复值合并数组?

Javascript:从字符串数组创建字典

swift - 无法识别 Swift 中的字典扩展