Search code examples
pythondictionarypython-3.6dictionary-comprehension

convert for loop into dictionary comprehension


I have a small program that works just fine. I am trying to force myself to review\analyze my code in order to try to make my code (and myself) just a little better.

I was wondering if this small portion of code:

temp2 = {}
for key in sorted(temp1.keys()):
    temp2[key] = temp1[key]

couldn't be rewritten as a dictionary comprehension.

Due primarily to my profound lack of experience I am not able to 'convert' this into a comprehension.

All the loop does is take dictionary temp1, sort it and place the newly sorted key:value pairs into temp2.

As I stated above, the whole thing works as is, but I am trying to learn spotting patterns where I can make improvements.


Solution

  • Directly translating this to a dictionary comprehension is easy:

    temp2 = {key: value for key, value in sorted(temp1.items())}
    

    In case you don't want to use the value as tie-breaker if the keys are equal you could also provide a key so you're only sorting based on the key:

    temp2 = {key: value for key, value in sorted(temp1.items(), key=lambda x: x[0])}
    

    Even though dictionaries are "ordered" in python-3.6 doesn't mean you should rely on it (the orderedness is officially just a side-effect!). Better to use an OrderedDict and be on the safe side:

    from collections import OrderedDict
    temp2 = OrderedDict([(key, value) for key, value in sorted(temp1.items(), key=lambda x: x[0])])