我有一个脚本,它构建多个字典,并将它们合并为一个字典,以返回给调用实体。要求是将每个字典追加到前一个字典的末尾。当我在我的PC (Windows10,Python3.x)上构建它时,它工作得很好,如下所示。
{
"Array Name": "SU73ARWVSPF01",
"storageSystemId": "22186",
"storageSystemName": "POD5_SU73ARWVSPF01",
"accessible": true,
"model": "VSP G1500",
"svpIpAddress": "10.185.35.37",
"firmwareVersion": "80-06-78-00/00",
"lastRefreshedTime": "2020-12-21 14:45:31",
"Pool List": {
"Pool-1": {
"storagePoolId": 11,
"label": "DATA",
"capacityInBytes": 590323982008320,
"usedCapacityInBytes": 422152148877312,
"availableCapacityInBytes": 168171833131008,
"usedSubscription": 83
},
"Pool-2": {
"storagePoolId": 12,
"label": "LOGS",
"capacityInBytes": 28142827732992,
"usedCapacityInBytes": 21991601995776,
"availableCapacityInBytes": 6151225737216,
"usedSubscription": 78
}
},
"SNMP Manager List": {
"SNMP-1": {
"name": "Test",
"ipAddress": "1.1.1.1"
},
"SNMP-2": {
"name": "Test1",
"ipAddress": "2.2.2.2"
}
},
"Hardware Alert List": {
"diskAlerts": false,
"powerSupplyAlerts": false,
"batteryAlerts": false,
"fanAlerts": false,
"portAlerts": false,
"cacheAlerts": false,
"memoryAlerts": false,
"processorAlerts": false
}
}然而,在将其移动到将运行实际程序的服务器(RHEL7,Python2.7)之后,字典的顺序被打乱了,如下所示。
{
"accessible": true,
"storageSystemName": "POD5_SU73ARWVSPF01",
"Hardware Alert List": {
"cacheAlerts": false,
"powerSupplyAlerts": false,
"portAlerts": false,
"processorAlerts": false,
"batteryAlerts": false,
"diskAlerts": false,
"fanAlerts": false,
"memoryAlerts": false
},
"SNMP Manager List": {
"SNMP-1": {
"ipAddress": "1.1.1.1",
"name": "Test"
},
"SNMP-2": {
"ipAddress": "2.2.2.2",
"name": "Test1"
}
},
"svpIpAddress": "10.185.35.37",
"storageSystemId": "22186",
"Array Name": "SU73ARWVSPF01",
"lastRefreshedTime": "2020-12-21 21:45:31",
"model": "VSP G1500",
"Pool List": {
"Pool-2": {
"usedSubscription": 78,
"label": "LOGS",
"usedCapacityInBytes": 21991601995776,
"storagePoolId": 12,
"availableCapacityInBytes": 6151225737216,
"capacityInBytes": 28142827732992
},
"Pool-1": {
"usedSubscription": 83,
"label": "DATA",
"usedCapacityInBytes": 422152148877312,
"storagePoolId": 11,
"availableCapacityInBytes": 168171833131008,
"capacityInBytes": 590323982008320
}
},
"firmwareVersion": "80-06-78-00/00"
}第一个命令的输出是我想要的结果,并通过使用
OUTPUT={}
OUTPUT.update(new Dict1), OUTPUT.update(new Dict2).... etc有没有办法避免字典被插入到另一本字典的中间而不是放在它的末尾?
发布于 2020-12-22 06:29:36
保持插入顺序的Python字典只是一个特性since Python 3.6 (尽管当时它们只是一个实现细节;替代的Python实现不必遵守这一点)。Starting from Python 3.7,这已经成为一种语言规范。
因为您在服务器上使用的是Python2.7,所以不能保证使用默认的dict类的字典顺序。您可以使用collections.OrderedDict类来确保记住插入顺序。
https://stackoverflow.com/questions/65400764
复制相似问题