我有字典:
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']
我该如何解决我的问题?
答案 0 :(得分: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()]