【发布时间】:2020-12-21 22:24:30
【问题描述】:
我有一个脚本可以构建多个字典并将它们合并为一个字典以返回调用实体。要求是将每个字典附加到前一个字典的末尾。当我在我的 PC(Windows 10、python 3.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
}
}
但是,在将其移动到将运行实际程序的服务器(RHEL 7、python 2.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
有没有办法避免字典被插入到另一个的中间而不是在它的末尾
【问题讨论】:
-
字典元素的顺序无关紧要。
-
如果你关心订单,你应该使用列表,而不是字典。
-
词典在 3.7 版之前确实保留了正式添加到其中的项目的顺序——所以这就是原因——但正如 @Barmar 所说,这不重要。
-
@martineau 他们记得插入的顺序,不清楚这如何适用于与
.update()合并。 -
@Barmar:当
updates改变了dict中已经存在的东西的值时,这些项目的顺序不会改变,如果项目是新的,那么它会被添加到当前末尾.我认为这可能在某处的文档中......
标签: python python-2.7 dictionary