python - 如何获取字典列表中所有人的名字?

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

我不断收到错误,但我几乎不知道从哪里开始。

最佳答案

试试这个:

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

然后调用 ('first_name', Students) 方法的输出将是以下值的列表: ['迈克尔'、'约翰'、'马克'、'KB']

关于python - 如何获取字典列表中所有人的名字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54591193/

相关文章:

python - 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素?

python - 在 Python 中使用多个条目格式化字典的正确方法

python - 使用 curve_fit 拟合接受一维数组输入并返回二维数组的函数的正确方法

python - sre_constants.error : nothing to repeat

python - 如何用(python)列表中的顺序替换数字

python - 如何在python 3中找到任意列表中缺失的数字?

java - Google Guava newConcurrentMap 基础实现

Python:对类使用文档测试

python - 使用 RedShift 作为额外的 Django 数据库

python:按子列表中的项目对列表列表进行排序