【问题标题】:Python: Finding dictionaries in a list that have some keys of another list of dictionariesPython:在具有另一个字典列表的某些键的列表中查找字典
【发布时间】:2017-04-23 03:47:43
【问题描述】:

我有两个很长的字典列表。我想在第二个列表中找到具有第一个字典列表中的键的字典,并根据另一个键将它们分开。列表一中的一些键是列表二中的值。

这是一个例子:

students = [{'123': [{'course1': 2}, {'course2': 2}]}, 
            {'124': [{'course1': 3}, {'course2': 4}]}, 
            {'125': [{'course1': 24}, {'course2': 12}]}, 
            {'126': [{'course1': 2}, {'course2': 24}]}, ...]

finals = [{'student_number':'123', 'exam':'passed',...},
          {'student_number':'124', 'exam':'ungraded',...},
          {'student_number':'125', 'exam':'failed',...}, ...]

在学生中存在的finally中查找student_numbers,并根据'exam'键将它们分开:

# Students who passed exam, 'exam' = 'passed'
passed_students = ['123', ...]

# Other Students
other_students = ['124', '125', ...]

【问题讨论】:

    标签: python list dictionary key


    【解决方案1】:

    我不太确定您的数据是否采用最佳格式,但鉴于您拥有的内容,以下代码将起作用:

    students = [{'123': [{'course1': 2}, {'course2': 2}]},
                {'124': [{'course1': 3}, {'course2': 4}]},
                {'125': [{'course1': 24}, {'course2': 12}]},
                {'126': [{'course1': 2}, {'course2': 24}]}]
    
    finals = [{'student_number':'123', 'exam':'passed'},
              {'student_number':'124', 'exam':'ungraded'},
              {'student_number':'125', 'exam':'failed'}]
    
    studentIDs = [i.keys()[0] for i in students]
    
    passed_students=[]
    other_students=[]
    for row in finals:
        snum = row['student_number']
        status = row['exam']
        if status=='passed' and snum in studentIDs:
            passed_students.append(snum)
        elif status!='passed' and snum in studentIDs:
            other_students.append(snum)
        else:
            print 'Student ID {0} not found in list.'.format(snum)
    

    【讨论】:

      【解决方案2】:

      列表推导的小练习:

      students = [{'123': [{'course1': 2}, {'course2': 2}]},
                  {'124': [{'course1': 3}, {'course2': 4}]},
                  {'125': [{'course1': 24}, {'course2': 12}]},
                  {'126': [{'course1': 2}, {'course2': 24}]}]
      
      finals = [{'student_number':'123', 'exam':'passed',},
                {'student_number':'124', 'exam':'ungraded',},
                {'student_number':'125', 'exam':'failed',},]
      
      # Extract student id numbers.
      student_ids = set(
          student_data.keys()[0]
          for student_data in students)
      
      # Restrict finals to the students that exist in students.
      students_with_finals = [
          final
          for final in finals
          if final['student_number'] in student_ids]
      
      passed_students = [
          final['student_number']
          for final in students_with_finals
          if final['exam'] == 'passed']
      
      other_students = [
          final['student_number']
          for final in students_with_finals
          if final['exam'] != 'passed']
      
      print('Passed students: {}'.format(passed_students))
      print('Other students: {}'.format(other_students))
      

      结果:

      Passed students: ['123']
      Other students: ['124', '125']
      

      看起来可以通过使用以学生 ID 作为键的字典来简化数据结构:

      students = {
          '123': [{'course1': 2}, {'course2': 2}],
          '124': [{'course1': 3}, {'course2': 4}],
          '125': [{'course1': 24}, {'course2': 12}],
          '126': [{'course1': 2}, {'course2': 24}],
      }
      
      finals = {
          '123': {'exam':'passed', 'points': 100},
          '124': {'exam':'ungraded'},
          '125': {'exam':'failed'},
      }
      

      【讨论】:

      • 感谢 Helko,您的解决方案比我写的要好,3 个嵌套的 for 循环 + 2 个嵌套的 if。
      【解决方案3】:
      >>> students = {'123':{'name':'Bonnie','course_1':2, 'course_2':2},
      ...             '124':{'name':'Jerry', 'course_1':3, 'course_2':4},
      ...             '125':{'name':'Bob', 'course_1':24, 'course_2':12},
      ...             '126':{'name':'Jill', 'course_1':2, 'course_2':24}}
      >>> finals = [{'num':'123', 'exam':'passed'},
      ...           {'num':'124', 'exam':'ungraded'},
      ...           {'num':'125', 'exam':'failed'}]
      >>> student_results = {'passed':[], 'ungraded':[], 'failed':[]}
      >>>
      >>> for final in finals:
      ...    student_results[final['exam']].append(students[final['num']])
      >>>        
      >>> # Print student results.
      >>> for result in ['passed', 'ungraded', 'failed']:
      ...     print "Students %s:" % result
      ...     for student in student_results[result]:
      ...         print "   " + student['name']
      ...
      Students passed:
         Bonnie
      Students ungraded:
         Jerry
      Students failed:
         Bob        
      

      【讨论】:

        猜你喜欢
        • 2021-05-31
        • 1970-01-01
        • 2022-06-23
        • 2021-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-14
        相关资源
        最近更新 更多