【问题标题】:getting part of dictionary by value in python在python中按值获取字典的一部分
【发布时间】:2021-05-03 02:00:00
【问题描述】:

我有字典:

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

我应该如何解决我的问题?

【问题讨论】:

    标签: python dictionary for-loop key key-value


    【解决方案1】:

    您可以改用字典推导:

    {k: d for k, d in teamDictionary.items() if d['team'] == 'C'}
    

    【讨论】:

      【解决方案2】:

      你应该使用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'}}
      

      【讨论】:

        【解决方案3】:
         print({key: values for key, values in teamDictionary.items() if values['team'] == 'C'}
        

        【讨论】:

          猜你喜欢
          • 2021-05-11
          • 2014-06-11
          • 2017-12-27
          • 2016-08-20
          • 2015-04-26
          • 2011-12-22
          • 2015-03-31
          相关资源
          最近更新 更多