首页 > 解决方案 > 解决方法字典排序

问题描述

通过快速研究,我发现没有办法真正对字典进行排序。但是有一些解决方法,我使用了用户 Malik在此处建议的解决方法。

我运行了这个测试并得到:

>>> 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}

这正是我正在寻找的行为。非常感谢任何帮助或建议。

但是,当我尝试将其合并到我的代码中时,没有任何变化。这是代码:

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'])

和输出:

{'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>}

我不知道可能是什么问题。

标签: pythondictionarydictionary-comprehension

解决方案


推荐阅读