2016-12-30 35 views
0

是否有可能使用collections.OrderedDict就像正常的字典句法,某種from __???__ import ???派生物,而不轉換現有的字典使用[(key, value), ..., ]?我有幾個嵌入式json的代碼,並希望保持秩序。collections.OrderedDict正常字典的語法

+0

我想從正常的字典語法構造collections.OrderedDict。也就是說,'x = {「A」:1,「B」:2};斷言類型(x)== collections.OrderedDict'。當然,第二個是False。那麼,是否有可能通過某種有點冒險的衍生物來實現它? – xosp7tom

+1

使用某種類型的文字語法將無助於解碼JSON;只需告訴'json.loads()'代碼在解碼時使用'OrderedDict'。看到重複。 –

回答

1

根本沒有collections.OrderedDict就可以有一個有序字典:只需升級到Python 3.6。

PEP 468, under Performance

注意:在Python 3.6字典是保序。這實際上消除了性能問題。

只需使用常規詞典。

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> {1:1, 2:2} 
{1: 1, 2: 2} 
>>> {2:2, 1:1} 
{1: 1, 2: 2} 

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> {1:1, 2:2} 
{1: 1, 2: 2} 
>>> {2:2, 1:1} 
{2: 2, 1: 1} 
+0

好的建議,考慮到升級不會破壞他們的代碼 –

+0

https://docs.python.org/3.6/whatsnew/3.6.html#pep-520-preserving-class-attribute-definition-order指出:'訂單保存這個新實現的方面被認爲是一個實現細節,不應該依賴'。 –

+0

@hiroprotagonist - 奇怪的是,PEP只是聲明'dict'現在是有序的,但是PEP的總結表明它是一個實現細節。 – TigerhawkT3