defaultdict中的元素更改顺序

问题描述 投票:0回答:1

我有一个简单的循环,它将新项目追加到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的位置已更改)

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

我正在运行Python 3.7.3

python python-3.7
1个回答
0
投票

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

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

import pprint
pprint(something, sort_dicts=False)
© www.soinside.com 2019 - 2024. All rights reserved.