2017-06-18 229 views
-1

我有一本字典(teamDictionary),其种植有名字,团队和团队成员的工作状态:与Python嵌套字典

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队的训练团队成员

在此先感谢!

+0

你尝试过自己吗? –

+0

我试过如果语句 - '如果teamDictionary ['team'] ==“A”和teamDictionary ['status'] =='离开':statusList = teamDictionary ['name']' – AFK

+0

...众多其他变化,但我不断收到错误,表明字典是不可能的。 – AFK

回答

3

我觉得列表理解你想要看起来干净的条件:

team_A_on_leave = [player['name'] for player in teamDictionary.values() 
        if player['team'] == 'A' 
        and player['status'] == 'leave'] 

其他2种情况是相似的列表内涵与不同的条件。

+0

像冠军一样工作;感谢L. Alvarez! – AFK

+0

不客气,AFK –

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'}} 

你只改变基于要在内部字典来检查值的条件。

+0

谢谢德米特里 - 我必须赶上自己的lambda事情;我是新的,但还没有完成。感谢您的帮助。 – AFK

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']