program tip

dict를 OrderedDict로 변환

radiobox 2020. 7. 25. 10:45
반응형

dict를 OrderedDict로 변환


collections.OrderedDict수업 사용에 문제가 있습니다. Raspberry Pi의 데비안 배포판 인 Raspbian에서 Python 2.7을 사용하고 있습니다. 텍스트 어드벤처를 나란히 비교하기 위해 두 개의 사전을 인쇄하려고합니다. 순서는 정확하게 비교하기 위해 필수적입니다. 내가 무엇을 시도하든 사전은 일반적인 순서대로 인쇄됩니다.

내 RPi에서 수행 할 때 얻을 수있는 내용은 다음과 같습니다.

import collections

ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship
# OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])

분명히 함수 호출을 인쇄하고 키와 값 그룹을 중첩 된 목록에 넣기 때문에 옳지 않은 것이 있습니다 ...

이것은 내 PC에서 비슷한 것을 실행하여 얻은 것입니다.

import collections

Joe = {"Age": 28, "Race": "Latino", "Job": "Nurse"}
Bob = {"Age": 25, "Race": "White", "Job": "Mechanic", "Random": "stuff"}

#Just for clarity:
Joe = collections.OrderedDict(Joe)
Bob = collections.OrderedDict(Bob)

print Joe
# OrderedDict([('Age', 28), ('Race', 'Latino'), ('Job', 'Nurse')])
print Bob
# OrderedDict([('Age', 25), ('Race', 'White'), ('Job', 'Mechanic'), ('Random', 'stuff')])

이번에는 순서가 맞지만 다른 것을 올바르게 인쇄해서는 안됩니까? (목록에 넣고 함수 호출을 보여줍니다.)

오류는 어디에서 발생합니까? 파이썬의 파이 버전과는 아무런 관련이 없습니다. 파이썬은 단지 리눅스 버전이기 때문입니다.


당신은 사전을 만드는 첫번째 다음에 그 사전을 전달 OrderedDict. Python 버전 <3.6 (*)의 경우 그렇게 할 때 순서가 더 이상 정확하지 않습니다. dict본질적으로 주문되지 않습니다.

대신 튜플 시퀀스를 전달하십시오.

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

인쇄 할 때 표시 되는 OrderedDict것은 표현 이며 완전히 정확합니다. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])단지 재현 가능한 표현으로 내용이 무엇인지 보여줍니다 OrderedDict.


(*): In the CPython 3.6 implementation, the dict type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict() for certain cases.


If you can't edit this part of code where your dict was defined you can still order it at any point in any way you want, like this:

from collections import OrderedDict

order_of_keys = ["key1", "key2", "key3", "key4", "key5"]
list_of_tuples = [(key, your_dict[key]) for key in order_of_keys]
your_dict = OrderedDict(list_of_tuples)

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

Here is the proposed solution:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)


Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

참고URL : https://stackoverflow.com/questions/15711755/converting-dict-to-ordereddict

반응형