我有一个字典(teamDictionary),其中包含团队成员的姓名,团队和状态:
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'}
}
如何查询字典词典,以便我可以获得以下名称:
提前致谢!
答案 0 :(得分:3)
我认为列表理解与你想要的条件看起来很干净:
team_A_on_leave = [player['name'] for player in teamDictionary.values()
if player['team'] == 'A'
and player['status'] == 'leave']
其他两个场景将是具有不同条件的类似列表推理。
答案 1 :(得分:0)
我们可以过滤字典:
keys = filter(lambda x: teamDictionary.get(x).get('team') == 'A' and teamDictionary.get(x).get('status') == 'Leave', teamDictionary)
filtered_a = {k: teamDictionary.get(k) for k in keys}
{1: {'name': 'Bob', 'status': 'Leave', 'team': 'A'},
4: {'name': 'Phil', 'status': 'Leave', 'team': 'A'}}
您只需根据要在内部词典中检查的值更改条件。
答案 2 :(得分:0)
你可以试试这个:
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'}
}
a_leave = [b['name'] for a, b in teamDictionary.items() if b['team'] == 'A' and b['status'] == 'Leave']
b_travel = [b['name'] for a, b in teamDictionary.items() if b['team'] == 'B' and b['status'] == 'Travel']
c_training = [b['name'] for a, b in teamDictionary.items() if b['team'] == 'C' and b['status'] == "Training']