[Tutor] Preserve Ordering in the Dict

Mark Lawrence breamoreboy at gmail.com
Tue May 4 12:54:41 EDT 2021


On 04/05/2021 05:30, jark AJ wrote:
> Hi All,
> 
>         I am using Python 2.7.
> I have a dictionary in the following format and when I print it, I get the
> result not in the same order as shown. I am looking to preserve the order.
> I looked at the ordered dict and sorted, however not able get the desired
> result. Could you please help if there is a way we can achieve this, thanks
> in advance!!
> 
> data = {
>            "name": "my_name",
>            "items": [
>                {"type": "type_name",
>                 "details": [
>                     {
>                         "key": "key_name",
>                         "value": "value_name"
>                     }
>                 ]
>                 }
>            ]
>        }
> 
> print(data)
> 
> 
> Current Result:
> 
> {'items': [{'type': 'type_name', 'details': [{'value': 'value_name', 'key':
> 'key_name'}]}], 'name': 'my_name'}
> 
> Desired Result:
> 
> {'name': 'my_name', 'items': [{'type': 'type_name', 'details': [{'key':
> 'key_name', 'value': 'value_name'}]}]}

This 
https://docs.python.org/2.7/library/collections.html#ordereddict-objects 
should just work so what went wrong when you tried it?


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list