CodexBloom - Programming Q&A Platform

Python Dictionary Not Retaining Order as Expected When Combined with List Comprehensions

๐Ÿ‘€ Views: 683 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-13
python dictionary list-comprehension Python

Can someone help me understand After trying multiple solutions online, I still can't figure this out. I've searched everywhere and can't find a clear answer... I'm working with an scenario with a Python dictionary not retaining the order of keys as expected when I'm trying to create it using a list comprehension. I'm using Python 3.8, and I want to generate a dictionary from a list of tuples, but the order seems to change unexpectedly. Hereโ€™s the code Iโ€™m employing: ```python pair_list = [(1, 'one'), (3, 'three'), (2, 'two')] my_dict = {key: value for key, value in pair_list} ``` After running this code, I check the order of the keys by printing `my_dict.keys()`, but I find that the output is not in the sequence I defined in `pair_list`. Hereโ€™s the output I'm seeing: ```python print(my_dict.keys()) # Output: dict_keys([1, 3, 2]) ``` I expected the order to be preserved as `(1, 3, 2)`. Iโ€™ve read that dictionaries preserve insertion order since Python 3.7, so I'm puzzled. I even tried explicitly sorting the list before creating the dictionary using this code: ```python pair_list_sorted = sorted(pair_list) my_dict_sorted = {key: value for key, value in pair_list_sorted} ``` However, that just sorts the keys numerically, which isn't what I want. I want to maintain the original order from `pair_list`. What am I missing here? Is there a way to ensure that the order of elements from the list of tuples is maintained in the resulting dictionary? I'd really appreciate any guidance on this. I'm working in a Windows 10 environment. Thanks for taking the time to read this!