字典的顺序每次都有所不同

use*_*222 0 python django dictionary

尽管使用OrderedDict,每次都会改变字典的顺序.我在views.py中写道

from collections import OrderedDict

from django.shortcuts import render
import json

def index(request):
    with open('./data/data.json', 'r') as f:
        json_dict = json.loads(f.read())
        json_data = OrderedDict()
        json_data = json_dict
    return render(request, 'index.html', {'json_data': json_data})
Run Code Online (Sandbox Code Playgroud)

我在index.html中写道

<html>
?<head>
?<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
  <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>
?<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css">
?</head>
?<body>
    <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;">
    {% for i in json_data.items.values %}
            <option>{{ i }}</option>
    {% endfor %}
    </select>
    <select name="type" id="type1">
    {% for j in json_data.type1.values %}
            <option>{{ j }}</option>
    {% endfor %}
    </select>
    <select name="type" id="type2">
    {% for k in json_data.type2.values %}
            <option>{{ k }}</option>
    {% endfor %}
    </select>
    <select name="type" id="type3">
    {% for l in json_data.type3.values %}
            <option>{{ l }}</option>
    {% endfor %}
    </select>
    <select name="type" id="type4">
    {% for m in json_data.type4.values %}
            <option>{{ m }}</option>
    {% endfor %}
    </select>

  </script>

  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

I&J&K&L&M的变量具有json_data的结果,但这种字典json_data是不order.For例子i{'items': [{'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}]}但向下钻取的顺序是B => C => d => AI想显示=> B => C => d.我认为这可以通过使用OrderedDict()完成,但它是错误的.我该如何解决这个问题?我该怎么写呢?

Dan*_*man 5

您所做的就是使用OrderedDict对象覆盖已解析的JSON; 这根本不起作用.

相反,如文档所示,您可以将该类作为object_pairs_hook参数传递:

json_dict = json.loads(f.read(), object_pairs_hook=OrderedDict)
Run Code Online (Sandbox Code Playgroud)