Python从字典中检索所有项目

时间:2016-01-19 02:17:39

标签: 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

2 个答案:

答案 0 :(得分:2)

三个问题:

  1. dictionary是一个局部变量,因此people函数无法看到它,因此global name 'dictionary' is not defined
  2. .get()按键查找,而非值,因此不会返回您想要的内容。
  3. 将年龄为整数的字符串'20'传递给年龄。
  4. 要解决#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']
    

答案 1 :(得分:1)

您无需创建字典即可获得所需的名称。使用list comprehension

>>> 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]
>>> [name for name, age in zip(names, ages) if age == 20]
['Rich', 'Heath']


>>> def people(target_age):
...     return [name for name, age in zip(names, ages) if age == target_age]
... 
>>> people(21)
['Bill', 'Franz']
>>> people(20)
['Rich', 'Heath']

如果要使用字典(以及生成字典的函数),请指定函数的返回值:

>>> def combine_lists_into_dict():
...     dictionary = dict(zip(names,ages))
...     return dictionary
... 
>>> dictionary = combine_lists_into_dict()
>>> [name for name, age in dictionary.items() if age == 20]
['Rich', 'Heath']

BTW,20'20'不同。通过20代替'20'

>>> 20 == '20'
False