如何在词典列表中获得所有人的名字?

时间:2019-02-08 11:11:57

标签: python list dictionary

从词典列表中获取值 创建一个函数iterateDictionary2(key_name, some_list),给定字典列表和键名,该函数为每个字典打印存储在该键中的值。例如,iterateDictionary2('first_name', students)应该输出:

    Michael
    John
    Mark
    KB

iterateDictionary2('last_name', students)应该输出:

    Jordan
    Rosales
    Guillen
    Tonel

下面是给定的字典列表。

`students = [
     {'first_name':  'Michael', 'last_name' : 'Jordan'},
     {'first_name' : 'John', 'last_name' : 'Rosales'},
     {'first_name' : 'Mark', 'last_name' : 'Guillen'},
     {'first_name' : 'KB', 'last_name' : 'Tonel'}
]`

我尝试了特定的定位print(students[0]['first_name']),以便至少向我展示我在词典列表中的工作位置,但我正在努力一次访问所有词典。

我的代码未完成,因为我正在努力解决这个问题。

def getValues(keyName, someList):
    for i in len(someList):


print(getValues('first_name', students))

我继续遇到错误,我几乎不知道从哪里开始。

4 个答案:

答案 0 :(得分:1)

尝试一下:

def iterateDictionary2(key_name, students):
    return [student[key_name] for student in students]

然后,为('first_name', students)调用方法的输出将是这些值的列表: ['Michael', 'John', 'Mark', 'KB']

答案 1 :(得分:0)

# method with two params a key and a  list
def iterateDictionary(key, students):
 for s in students:
    print(s[key])

# a list
students = [
     {'first_name':  'Michael', 'last_name' : 'Jordan'},
     {'first_name' : 'John', 'last_name' : 'Rosales'},
     {'first_name' : 'Mark', 'last_name' : 'Guillen'},
     {'first_name' : 'KB', 'last_name' : 'Tonel'}
]


# printing the first names
print("Printing First names ..")

# calling the method with a key (first_name) and a list    
iterateDictionary('first_name', students)

# printing the last names
print("Printing Last names ..")

# calling the method with a key (last_name) and a list
iterateDictionary('last_name', students)

输出:

Printing First names ..
Michael
John
Mark
KB
Printing Last names ..
Jordan
Rosales
Guillen
Tonel

编辑:

如果要将它们打印在列表中:

def iterateDictionary(key, students):
        print([s[key] for s in students])

输出:

Printing First names ..
['Michael', 'John', 'Mark', 'KB']
Printing Last names ..
['Jordan', 'Rosales', 'Guillen', 'Tonel']

答案 2 :(得分:0)

#students = [
#     {'first_name':  'Michael', 'last_name' : 'Jordan'},
#     {'first_name' : 'John', 'last_name' : 'Rosales'},
#     {'first_name' : 'Mark', 'last_name' : 'Guillen'},
#     {'first_name' : 'KB', 'last_name' : 'Tonel'}
#]

def iterateDictionary2(key_name, some_list):
    for d in some_list:
        print(d[key_name])


iterateDictionary2('first_name', students)
#Michael
#John
#Mark
#KB

iterateDictionary2('last_name', students)
#Jordan
#Rosales
#Guillen
#Tonel

答案 3 :(得分:0)

def get_first_name_list(students):
    return [st['first_name'] for st in students if  'first_name' in st]

这将起作用,在此代码中检查字典的列表具有“ first_name”键,如果字典具有“ first_name”键,则first_name的值将附加在列表中。 并且列表将返回。