根据日期时间对字典中的数组进行排序

时间:2020-09-22 10:19:59

标签: python arrays json python-3.x

我想基于versions键对modified_datetime数组进行排序。我绝对可以使用一种排序算法来做到这一点,但我只是想知道是否有一种有效的方法可以在Python中做到这一点。

my_json = {
  "versions": [
    {
      "migrated_versions": [ 
        {
          "modified_datetime": "2020-09-11T21:15:22.215Z"
        }
      ],
    },
    {
      "migrated_versions": [ 
        {
          "modified_datetime": "2020-09-11T21:14:19.162Z"
        }
      ]
    },
    {
      "migrated_versions": [ 
        {
          "modified_datetime": "2020-09-11T21:10:19.289Z"
        }
      ]
    }
  ]
}

1 个答案:

答案 0 :(得分:3)

由于日期时间是按字典顺序排序的ISO8601,因此您可以将sorted()内置的list.sort()(或key=)与sorted(my_json["versions"], key=lambda v: v["migrated_versions"][0]["modified_datetime"]) 参数一起使用:

         <mat-selection-list #rolesSelection
                  class="checkbox-list"
                  [formControlName]="formControlName"
                  required>
             <div class="builder-role" *ngFor="let role of roles; index as i">
               <mat-list-option class="checkbox-list-option"
                   checkboxPosition="before"
                   (click)="onRoleSelect(role)"
                   (keyup.enter)="onRoleSelect(role)"
                   (keyup.space)="onRoleSelect(role)"
                   [value]="role">
               {{role.getName()}}
            </mat-list-option>
            <mat-form-field *ngIf="shouldShowControl(role.getRoleId())"
                  class="builder-students">
          <input appDigitOnly
           i18n-aria-label
           matInput
           aria-label="Number of students"
           max="{{maxNumberOfStudents}}"
           min="1"
           name="{{role.getRoleId()}}"
           type="number"
           value="{{getNumStudents(role)}}"
           [formControlName]="role.getRoleId()"
           [errorStateMatcher]="matcher"
           (change)="setStudents($event.target.value, role)">
        </mat-form-field>
       </div>
      </mat-selection-list>