Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Casting a sorted list to dictionary, difference in Google Colab and Pycharm

chars = dict(sorted(crops.items(),key=lambda kv: kv[1].size, reverse=True)[:4])

I am creating a dictionary, chars, that maps count variables (any integer vals) to my four largest crop values from a previous dictionary, crops.

I am running the above line in both Google Colab and Pycharms and it gives me a different dictionary in each. In Colab, it gives me what I want, from the list seen below (Note: lots of lines were taken out of the list). It retains the order of the list { (6, crop1), (7,crop2) , (2, crop3) , (3, crop4) } .

However, in pycharms the output is { (2, crop3) , (3, crop4), (6, crop1), (7,crop2)} , where it is still getting the largest four crops, but by casting it to dict() it seems to reorder my list in the dictionary by the count variables.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Chars list:

[(6, array([[78, 76, 77, 78, 73, 81, 80, 81, 79, 72, 77, 78, 71, 73, 78, 81,
        82, 79, 76, 74, 75, 85, 86, 78, 76, 84, 85, 80, 78, 73, 76],
      ..., (7, array([[89, 90, 87, 83, 82, 83, 77, 76, 75, 74, 71, 73, 74, 77, 77, 80,
        77, 75..., (3, array([[ 79,  77,  81,  74,  80,  85,  83,  79,  74,  77,  74,  76,  78,
        ...]

I am not sure what is causing this and could definitely use some help. Maybe an issue is also for PyCharms the code is running realtime in a Gazebo simulation, so maybe that changes how dict() is casting my list?

>Solution :

Dictionaries are an inheritently unordered data structure – period.

Dictionaries in python (*) are insert sorted – the first item put into it is also the first printed.

(*) holds for python 3.7 and above – below 3.7 dicts may be randomly sorted or (implementation detail) be insert sorted as well.

If you get different sortings you either insert in a different order OR run wildly different versions of python.

How do I detect the Python version at runtime?

In case you use an earlier version of python >= 3.1 you can use collections.ordereddict

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading