通过键从字典中获取值数组

时间:2021-01-29 11:26:17

标签: python arrays dictionary return-value

我有字典:

teamDictionary = {
1: {'name': 'Bob', 'team': 'A', 'status': 'Leave'},
2: {'name': 'George', 'team': 'C', 'status': 'Training'},
3: {'name': 'Sam', 'team': 'B', 'status': 'Travel'},
4: {'name': 'Phil', 'team': 'A', 'status': 'Leave'},
5: {'name': 'Georgia', 'team': 'C', 'status': 'Training'}
}

我需要获取名称数组:

['Bob','George','Sam','Phil','Georgia']

我该如何解决我的问题?

4 个答案:

答案 0 :(得分:2)

使用列表理解,你可以

  1. 获取字典中的值。
  2. 对于每个值,获取 name
TeamDictionary = {
1: {'name': 'Bob', 'team': 'A', 'status': 'Leave'},
2: {'name': 'George', 'team': 'C', 'status': 'Training'},
3: {'name': 'Sam', 'team': 'B', 'status': 'Travel'},
4: {'name': 'Phil', 'team': 'A', 'status': 'Leave'},
5: {'name': 'Georgia', 'team': 'C', 'status': 'Training'}
}
print([x['name'] for x in TeamDictionary.values()])
> ['Bob', 'George', 'Sam', 'Phil', 'Georgia']

答案 1 :(得分:1)

这会起作用:

names = [value['name'] for key, value in teamDictionary.items()]

答案 2 :(得分:0)

您可以遍历字典键,对于每个项目,您可以“获取”名称属性,例如:

names = [teamDictionary[key]['name'] for key in teamDictionary]

答案 3 :(得分:0)

您可以使用数组推导在一行中轻松完成此操作。

names = [item['name'] for item in teamDictionary.values()]