ordereddict dict python ordereddictionary

python - Conversión de dic a OrderedDict



ordereddict python 3 (4)

La mayoría de las veces elegimos OrderedDict cuando solicitamos un pedido personalizado, no uno genérico como ASC, etc.

Aquí está la solución propuesta:

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

Esto se generará:

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

Nota : Los nuevos diccionarios ordenados mantienen su orden de clasificación cuando se eliminan las entradas. Pero cuando se agregan nuevas claves, las claves se agregan al final y no se mantiene el orden. ( Doc oficial )

Tengo problemas para usar las collections.OrderedDict . Clase DderedDict. Estoy usando Python 2.7 en Raspbian, la distribución de Debian para Raspberry Pi. Intento imprimir dos diccionarios para comparar (lado a lado) para una aventura de texto. El orden es esencial para comparar con precisión. No importa lo que intento, los diccionarios se imprimen de la manera desordenada habitual.

Esto es lo que obtengo cuando lo hago en mi 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)])

Obviamente, hay algo incorrecto porque está imprimiendo la llamada a la función y poniendo las claves y los grupos de valores en una lista anidada ...

Esto es lo que obtuve al ejecutar algo similar en mi 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'')])

Esta vez, está en orden, pero no debería estar imprimiendo las otras cosas, ¿verdad? (Poniéndolo en la lista y mostrando la función llamada).

¿Dónde estoy cometiendo mi error? No debería tener nada que ver con la versión pi de Python porque es solo la versión de Linux.


Sé que es una publicación anterior, pero recientemente tuve que lidiar con algo así, solo que era más complejo.

Ambas respuestas son buenas dependiendo de cuál es tu objetivo final. Quiero mencionar que es una diferencia importante entre las 2 respuestas proporcionadas por @Martijn y @Abdul.

Si miras sus respuestas, la forma en que construyen el diccionario es diferente. @Martijn usa una lista de tuplas, mientras que @Abdul usa la forma más estándar de definir diccionarios en Python.

Donde puedes ver esto es cuando tienes un diccionario con varios niveles, como este:

dict = {"key": value, {"key_2": value_2, {"key_3": value_3 } } }

Si elige la respuesta @Abdul, puede iterar fácilmente sobre una subdivisión simplemente haciendo un seguimiento de las claves, pero la respuesta @Martijn le dará un diccionario con listas dentro de las cuales no es fácil de iterar (necesita bucles, etc.).

Nuevamente, depende de la complejidad de la aplicación. Recientemente me encontré con una situación en la que necesitaba un OrderedDict y para iterar sobre su clave de subcódigos en cualquier nivel. El objetivo de los diccionarios en Python es ir a los valores simplemente buscando una clave específica.

El siguiente ejemplo fue construido por mí al analizar varios archivos XML y anexarlos a un diccionario vacío. Después de obtener el dict como ves, tuve que verificar cada sub-dict para ciertas condiciones.

{ "_id" : "structhse_message__t_1a53d12f4c7e5dcbfc75d9ed20cdd11d70", "refid" : "structhse_message__t_1a53d12f4c7e5dcbfc75d9ed20cdd11d70", "kind" : "variable", "name" : "loadPlainKeyReq", "last_modified" : ISODate("2017-08-29T07:17:45.361Z"), "member_0" : { "_id" : "hseLoadPlainKeyCmd_t", "refid" : "structhse_load_plain_key_cmd__t", "type_name" : "hseLoadPlainKeyCmd_t", "parent_name" : "loadPlainKeyReq", "member_0" : { "_id" : "structhse_load_plain_key_cmd__t_1a283b970e7bd46c62343ea893a86f075e", "refid" : "group___h_s_e___types_1ga7e573d098b9f292a1794a56b02a05b15", "type_name" : "hseKeyId_t", "name" : "overwritekeyId" }, "member_1" : { "_id" : "structhse_load_plain_key_cmd__t_1a613df97c7a4c9e21a3f3228ec1eea1b4", "refid" : "unionhse_key_formats__t", "type_name" : "hseKeyFormats_t", "name" : "loadKey", "member_0" : { "_id" : "unionhse_key_formats__t_1ac56e6b68b9024796ae1ecdefe2c7a3bb", "refid" : "group___h_s_e___types_1ga8086fa2f11c7328996de2854960976c8", "type_name" : "hseKeyType_t", "name" : "keyType" }, "member_1" : { "_id" : "unionhse_key_formats__t_1abe287bb206fb6def7c6cd77cfca5a4a0", "refid" : "structhse_sym_key__t", "type_name" : "hseSymKey_t", "name" : "sheKey", "member_0" : { "_id" : "structhse_sym_key__t_1a2d3fbac1c274c7b6b4aa12c4bd322739", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "numBytes" }, "member_1" : { "_id" : "structhse_sym_key__t_1ad3d9f7a1483bee99c3865f5bbaf78c2d", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "symKey_Addr" } }, "member_2" : { "_id" : "unionhse_key_formats__t_1add390730769274485feffa5052ce5fca", "refid" : "structhse_sym_key__t", "type_name" : "hseSymKey_t", "name" : "symKey", "member_0" : { "_id" : "structhse_sym_key__t_1a2d3fbac1c274c7b6b4aa12c4bd322739", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "numBytes" }, "member_1" : { "_id" : "structhse_sym_key__t_1ad3d9f7a1483bee99c3865f5bbaf78c2d", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "symKey_Addr" } }, "member_3" : { "_id" : "unionhse_key_formats__t_1aa63deae0529b46f313a9baaee9f24105", "refid" : "structhse_ecc_priv_key__t", "type_name" : "hseEccPrivKey_t", "name" : "eccPrivKey", "member_0" : { "_id" : "structhse_ecc_priv_key__t_1af2fa59d39cb2257b12befcc190205785", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "numBytes" }, "member_1" : { "_id" : "structhse_ecc_priv_key__t_1aaff2312cfc5bd209457b371e83fabfa3", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "privKey_Addr" } }, "member_4" : { "_id" : "unionhse_key_formats__t_1a5a020d8aa302adfb83599f6b0be395cc", "refid" : "structhse_ecc_pub_key__t", "type_name" : "hseEccPubKey_t", "name" : "eccPubKey", "member_0" : { "_id" : "structhse_ecc_pub_key__t_1a7e137100290802efe4ca122a4b155175", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "numBytes" }, "member_1" : { "_id" : "structhse_ecc_pub_key__t_1aacb70aae75409136c83b43e3bf592f7f", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "pubKey_Addr" } }, "member_5" : { "_id" : "unionhse_key_formats__t_1ada8568ccaf5bb966daf83a95f2c5f5b6", "refid" : "structhse_rsa_priv_key__t", "type_name" : "hseRsaPrivKey_t", "name" : "rsaPrivKey", "member_0" : { "_id" : "structhse_rsa_priv_key__t_1a10f71bff068bf3df19e087eac57a584a", "refid" : "group___h_s_e___types_1ga9b2050e928b8f19bc2e54120ec560262", "type_name" : "hseRsaPrivKeyFormat_t", "name" : "rsaPrivKeyFormat" }, "member_1" : { "_id" : "structhse_rsa_priv_key__t_1a96b14335070d33861191e6aea1c07992", "refid" : "structhse_rsa_priv_key_crt__t", "type_name" : "hseRsaPrivKeyCrt_t", "name" : "rsaPrivKeyCrt", "member_0" : { "_id" : "structhse_rsa_priv_key_crt__t_1ab7709493289cc1671848f08a65960c6c", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "p", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_1" : { "_id" : "structhse_rsa_priv_key_crt__t_1a1211b6edca95a24aaa33aefc0af08a06", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "q", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_2" : { "_id" : "structhse_rsa_priv_key_crt__t_1ae458aa8cf28b88c4665d3d716b727376", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "dp", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_3" : { "_id" : "structhse_rsa_priv_key_crt__t_1a80937dde3f726c674be5861f8a3db0f9", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "dq", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_4" : { "_id" : "structhse_rsa_priv_key_crt__t_1ae83e11e22974815337d5eda88152878c", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "qInv", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } } }, "member_2" : { "_id" : "structhse_rsa_priv_key__t_1a0d73e9ee22b811fa0e41751b71bbd853", "refid" : "structhse_rsa_priv_key_plain__t", "type_name" : "hseRsaPrivKeyPlain_t", "name" : "rsaPrivKeyPlain", "member_0" : { "_id" : "structhse_rsa_priv_key_plain__t_1a3122040fccdfe86987c4e251071e0a46", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "n", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_1" : { "_id" : "structhse_rsa_priv_key_plain__t_1ad0fb7fa8d05ccbb86eabfa1bf9b8718c", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "d", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } } }, "member_3" : { "_id" : "structhse_rsa_priv_key__t_1a5d64e4c273782cc2cfad162149aea5b5", "refid" : "union", "type_name" : "rsaFormat", "name" : "rsaFormat" } }, "member_6" : { "_id" : "unionhse_key_formats__t_1a73c29b0545c73d630db6c5978421d155", "refid" : "structhse_rsa_pub_key__t", "type_name" : "hseRsaPubKey_t", "name" : "rsaPubKey", "member_0" : { "_id" : "structhse_rsa_pub_key__t_1a2a3a2a17b9b8cb3bb4d654917adc2a69", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "n", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } }, "member_1" : { "_id" : "structhse_rsa_pub_key__t_1ae5a520f45a29b7ba435e062e58c5aecd", "refid" : "structhse_m_p_int__t", "type_name" : "hseMPInt_t", "name" : "e", "member_0" : { "_id" : "structhse_m_p_int__t_1a0d231d88b38942f8015f10de758a9a3b", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "umBytes" }, "member_1" : { "_id" : "structhse_m_p_int__t_1a6e2c91b8343a37fd2fa74b2acd9b3de7", "refid" : "group___h_s_e___types_1gac65702985a8ebfca3036aebd0d9e5cff", "type_name" : "buffer_t", "name" : "MPInt_Addr" } } }, "member_7" : { "_id" : "unionhse_key_formats__t_1ae5d8530608ceb16796bc5309e0f979e5", "refid" : "group___h_s_e___types_1ga1347949493721c164d500d649123609f", "type_name" : "hseEccDhSecret_t", "name" : "eccDHSecret" }, "member_8" : { "_id" : "unionhse_key_formats__t_1af9f446849a3751621a0eddba8ecb6d07", "refid" : "group___h_s_e___types_1gae4897cc586402c5dd8a23125a3528740", "type_name" : "hseDhSecret_t", "name" : "dhSecret" }, "member_9" : { "_id" : "unionhse_key_formats__t_1a0b387adc00cb2e8ab10c36bf56a811d4", "refid" : "union", "type_name" : "keyFormat", "name" : "keyFormat" } }, "member_2" : { "_id" : "structhse_load_plain_key_cmd__t_1a1c4ec69f75f3e8dcd1666ede97d65022", "refid" : "structhse_key_info_flags__t", "type_name" : "hseKeyInfoFlags_t", "name" : "keyInfo", "member_0" : { "_id" : "structhse_key_info_flags__t_1a9cc5afac809e83a7bfdc55531fed9c53", "refid" : "group___h_s_e___types_1ga76a0191e789df1f47b4ac84ea612f7bb", "type_name" : "hseKeyMemTarget_t", "name" : "keyMemTarget" }, "member_1" : { "_id" : "structhse_key_info_flags__t_1ac3c1d57b55a13979d8d521a266ff7f58", "refid" : "group___h_s_e___types_1ga1134b580f8da4de94ca6b1de4d37975e", "type_name" : "uint32", "name" : "keyUsage" }, "member_2" : { "_id" : "structhse_key_info_flags__t_1a46a26062e5eaa0bd1fdf17596409cb56", "refid" : "group___h_s_e___types_1gaa2e9e15da1391eafeeb2c5c57dfee278", "type_name" : "hseKeyRA_t", "name" : "ra" }, "member_3" : { "_id" : "structhse_key_info_flags__t_1a5479c6b76ad1716839561f56bb7c62b8", "refid" : "group___h_s_e___types_1ga3534a0c18a0013fa5f8cbce405ed4713", "type_name" : "hseKeyWA_t", "name" : "wa" } }, "member_3" : { "_id" : "structhse_load_plain_key_cmd__t_1aa901f13e8ba971e748258ca603a8e7fb", "refid" : "group___h_s_e___types_1ga7e573d098b9f292a1794a56b02a05b15", "type_name" : "hseKeyId_t", "name" : "keyId_Addr" }, "last_modified" : ISODate("2017-08-29T07:18:36.796Z") } }


Si no puede editar esta parte del código donde se definió su dict todavía puede pedirlo en cualquier punto de la forma que desee, como esta:

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)


Primero está creando un diccionario y luego pasando ese diccionario a un OrderedDict . Para cuando lo haga, el orden ya no será correcto. dict está inherentemente ordenado.

Pase en una secuencia de tuplas en su lugar:

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

Lo que ves cuando imprimes OrderedDict es su representación , y es completamente correcto. OrderedDict([(''PRICE'', 250), (''HP'', 50), (''NAME'', ''Albatross''), (''BLASTERS'', 13), (''THRUSTERS'', 18)]) simplemente te muestra, en una representación reproducible , cuáles son los contenidos del OrderedDict .