2017-06-18 16 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のEAMメンバー

    ありがとうございます!

  • +0

    あなたは自分を試してみましたか? –

    +0

    私はif文を試しました - 'teamDictionary ['team'] ==" A "とteamDictionary ['status'] == 'Leave':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.アルバレス! – 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

    ドミトリーありがとうございました - 私はラムダ事に自分自身をキャッチする必要があります。私は新しく、まだそこにはかなりありません。助けてくれてありがとう。 – 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'] 
    
    関連する問題