python dict 排序

2种方法:

  1. ordereddict

    import ordereddict;

    aa = ordereddict.OrderedDict()

    然后就可以像正常一样用dict了。至于ordereddict怎么安装:

    下载模块:https://pypi.python.org/pypi/ordereddict/,解压:tar xf ${thirdparty_dir}/ordereddict-1.1.tar.gz

    安装:cd ordereddict-1.1 && sudo python setup.py install

  2. 按key排序

    这个应该比较常用,不用装模块,使用场景也比较多

    假设aa = 

    {

        "11": ["ctl"],

        "12": ["cnc"],

        "13": ["cmb"],

        "14": ["cuc"],

        "15": ["crc"],

        "17": ["dxt"],

        "18": ["cer"],

        "19": ["bgctv", "colnet", "citic", "ehome", "fbwn", "gdvnet", "gwbn", "wasu", "twnet", "other"],

        "20": ["oversea"]

    }

    for key, value in sorted(aa.keys()):

                print key, value



你可能感兴趣的:(python dict 排序)