defaultdict 中的元素更改顺序

Elements in defaultdict change order

我有一个简单的循环,它将新项目附加到 defaultdict(list):

import spacy
from collections import defaultdict
import json
from pprint import pprint

def run():
   nlp = spacy.load('en_core_web_sm')
   doc = nlp(sentence)
   sentence = "Hi my name is Oliver!"
   ners = defaultdict(list)
   ners['text'] = str(sentence)

   #Simply loop:
   for ent in doc.ents:
       ners['extractions'].append({
            "label": str(ent.label_),
            "text": str(ent.text),
            "confidence": round(score, 2),
            "start_position": ent.start_char,
            "end_position": ent.end_char
       })

   #Print out the defaultdict.
   pprint(ners)

以上打印出来:

{
   "extractions":[
      {
         "confidence":1.0,
         "end_position":20,
         "label":"PERSON",
         "start_position":14,
         "text":"Oliver"
      }
   ],
   "text":"Hi my name is Oliver"
})

可以看到,按键的顺序和循环中的顺序不一样(比如end_positionstart_position换了地方)

如何保持与我在代码中编写的顺序相同的输出顺序?

我是运行Python3.7.3.

正如 martineau 所说,pprint() 在打印时默认对键进行排序。

在 Python 3.8+ 中,您可以添加 sort_dicts=False 来禁用此功能:

import pprint
pprint(something, sort_dicts=False)