【问题标题】:getting arrays of values from dictionary by key按键从字典中获取值数组
【发布时间】:2021-01-29 11:26:17
【问题描述】:

我有字典:

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

我需要获取名称数组:

['Bob','George','Sam','Phil','Georgia']

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

【问题讨论】:

    标签: python arrays dictionary return-value


    【解决方案1】:

    你可以使用列表推导

    1. 获取字典中的值。
    2. 对于每个值,获取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'}
    }
    
    print([x['name'] for x in TeamDictionary.values()])
    > ['Bob', 'George', 'Sam', 'Phil', 'Georgia']
    

    【讨论】:

      【解决方案2】:

      这将起作用:

      names = [value['name'] for key, value in teamDictionary.items()]
      

      【讨论】:

        【解决方案3】:

        您可以遍历字典键,并为每个项目“获取”名称属性,例如:

        names = [teamDictionary[key]['name'] for key in teamDictionary]
        

        【讨论】:

          【解决方案4】:

          您可以使用数组理解在一行中轻松完成此操作。

          names = [item['name'] for item in teamDictionary.values()]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-01-27
            • 1970-01-01
            • 2011-12-22
            相关资源
            最近更新 更多