Python将对象添加到字典

时间:2018-08-21 14:16:59

标签: python json dictionary collections

我有一个JSON对象,我想将其添加到现有的JSON对象中。当我添加对象时,即使代码首先添加了新对象,它也被添加到JSON的底部。

这是JSON的示例...

Applicative

这就是我想要JSON的样子。 ID和Description应该在ItemInvolvesShortfall之前。

{
    "Header": {
        "ID": "Bob",
        "Description": "Description header_dict"
    },
    "Body": {
        "ItemInvolvesShortfall": {
            "SpecifiedBy": {
                "category": "Fibre To The Node",
                "version": "1.2.0",
                "type": "Shortfall Specification",
                "ID": "FTTN Shortfall"
            },
            "DescribedBy": {
                "Characteristic": {
                    "type": "Automatically fulfillable",
                    "ID": "pillar-patch"
                },
                "value": "Yes"
            }
        },
        "ID": "Bob",
        "Description": "Description body_dict"
    }
}

这是代码段。

….
"Body": {
        "ID": "Bob",
        "Description": "Description body_dict",
"ItemInvolvesShortfall": {
            "SpecifiedBy": {
                "category": "Fibre To The Node",
                "version": "1.2.0",
                "type": "Shortfall Specification",
                "ID": "FTTN Shortfall"
            },
            "DescribedBy": {
                "Characteristic": {
                    "type": "Automatically fulfillable",
                    "ID": "pillar-patch"
                },
                "value": "Yes"
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

Python(和大多数其他语言)的字典没有顺序-它们是key:value对的集合(无序集合)。因此,以数据结构具有顺序为前提的假设是错误的,认为它们顺序错误的说法是错误的。