使用Python嵌套字典
我有一个字典teamDictionary,其中包含团队成员的姓名、团队和状态:使用Python嵌套字典,python,dictionary,Python,Dictionary,我有一个字典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':
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中休假的所有团队成员,或
B组中处于旅行状态的所有团队成员,或
C组所有正在接受培训的团队成员
提前谢谢 我认为列出你想要的条件的理解会很清楚:
team_A_on_leave = [player['name'] for player in teamDictionary.values()
if player['team'] == 'A'
and player['status'] == 'leave']
其他两种情况是类似的列表理解,但条件不同。我们可以筛选字典:
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'}}
您只需根据要在内部字典中检查的值更改条件。您可以尝试以下操作:
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']
你自己试过什么?我试过if语句-if teamDictionary['team']==A和teamDictionary['status']='Leave':statusList=teamDictionary['name']..还有许多其他变体,但我不断收到错误,表明字典不易损坏。威廉,我不确定我做了什么值得你担心。。。顺便说一句,你一下子否决了我的问题,它就在你个人资料上的评论面前飞过,然后你删除了你的回复,因为它不是我选择使用的那个?我从与你的互动中了解到——我未来的帖子会更好,并包含更多关于我尝试过的内容;所以,谢谢你。我没有把你的帖子录下来。。。正如我在个人资料页面上写的那样,我通常会首先评论应该改进的地方。谢谢Dmitry——我必须赶上lambda的事情;我是新来的,只是还不太适应。谢谢你的帮助。