Through quick research I found out that there is no way to truly sort a dictionary. However there are workarounds and I used the one suggested here by user Malik.
I ran this test and got:
>>> test={"im2":1,"im4":2,"im3":-1,"im1":5}
>>> {x:test[x] for x in sorted(test)}
{'im1': 5, 'im2': 1, 'im3': -1, 'im4': 2}
which is exactly the behaviour I'm looking for. Any help or suggestion is greatly appreciated.
However, when I try to incorporate it into my code, nothing changes. Here's the code:
def loop_solution(filenames):
mydic={'im'+str(index): import_file_astro(filename) for index, filename in enumerate(filenames, start=1) if filename is not None}
print mydic
mydic_upd={'im'+str(i):mydic.values()[0] for i in range(1,5) if 'im'+str(i) not in mydic}
mydic=dict(mydic, **mydic_upd)
print mydic
mydic={y:mydic[y] for y in sorted(mydic)}
print mydic
return
loop_solution([None,'CO21_m100_100_final',None,'CO43_m100_100_final'])
and the output:
{'im2': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im4': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0>}
{'im1': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im3': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im2': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im4': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0>}
{'im1': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im3': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im2': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b6dc690>, 'im4': <astropy.io.fits.hdu.image.PrimaryHDU object at 0x11b7461d0>}
I'm at a loss of what could be the problem.