我有字典:
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'}
}
我需要得到所有较小的字典,其中团队是c。我的cod是:
team_leave = [teamDictionary[a] for a, b in teamDictionary.items() if b['team'] == 'C' ]
print(team_leave)
[{'name': 'George', 'team': 'C', 'status': 'Training'}, {'name': 'Georgia', 'team': 'C', 'status': 'Training'}]
但是我需要得到
{
2: {'name': 'George', 'team': 'C', 'status': 'Training'},
5: {'name': 'Georgia', 'team': 'C', 'status': 'Training'}
}
我该如何解决我的问题?
您可以使用字典推导式:
{k: d for k, d in teamDictionary.items() if d['team'] == 'C'}
你应该使用Dictionary Comprehension:
team_leave = {key: item for key, item in teamDictionary.items() if item['team'] == 'C'}
print(team_leave)
输出:
{2: {'name': 'George', 'team': 'C', 'status': 'Training'}, 5: {'name': 'Georgia', 'team': 'C', 'status': 'Training'}}
print({key: values for key, values in teamDictionary.items() if values['team'] == 'C'}