在字典Python中对键进行排序

时间:2017-06-06 10:37:21

标签: python sorting dictionary

我有一个像这样的Json文件:

{
  "wasGeneratedBy": {
    "_:wGB3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "stcsiNum-1b"
    },
    "_:wGB1": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444-cutouts",
      "prov:activity": "cds_cutout444"
    },
    "_:wGB2": {
      "prov:entity": "ivo://stsci/DSS-digitized-I.444",
      "prov:activity": "stcsiNum-1a"
    }
  },
  "activity": {
    "stcsiNum-1a": {},

  },
  "used": {
    "_:u6": {
      "prov:entity": "ivo://stsci/DSS-Plate-R.444",
      "prov:activity": "stcsiNum-1c"
    },
    "_:u2": {
      "prov:entity": "ivo://stsci/DSS-Plate-I.444",
      "prov:activity": "stcsiNum-1a"
    },
    "_:u3": {
      "prov:entity": "ivo://stsci/DSS-digitized-J.444",
      "prov:activity": "cds_cutout444"

  },
  "entity": {
    "ivo://stsci/DSS-digitized-R.444": {},
    "ivo://stsci/DSS-digitized-J.444-cutouts": {},
    "ivo://stsci/DSS-Plate-R.444": {},
  }
}

但是我想按照这样的特定顺序(“活动”,“实体”,“使用”,“wasGeneratedBy”)对所有键(“wasGenereratedBy”,“activiy”...)进行排序。

我已声明:

my_own_order = ['entity', 'used', 'activity','wasGeneratedBy']

我试过这个,但是不起作用:

print sorted(fileName,order=my_own_order)

有什么建议吗?谢谢你

1 个答案:

答案 0 :(得分:5)

使用OrderedDict

from collections import OrderedDict

print OrderedDict((k,mydict[k] for k in  my_own_order))