关于python:按字母顺序按键对字典排序

Sort dictionary by key alphabetically

本问题已经有最佳答案,请猛点这里访问。

我的dictionary无法按其keys的字母顺序排序。

以下是我的代码:

1
2
3
4
5
6
7
8
9
10
11
colorSizes = {'Rust': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
              'Middle Blue': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
              'Grey': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
              'Aqua': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16', 'SIZE 18'],
              'Navy': ['SIZE 8', 'SIZE 10', 'SIZE 12', 'SIZE 14', 'SIZE 16']}

realColor = {}
for key in sorted(colorSizes.keys()):
    realColor[key] = colorSizes.get(key)

print(realColor)

我得到什么:

{'Yellow/Fuschia':['Large', 'Extra Large'],
'Black':['Small', 'Medium', 'Large']}

我想要的是:

{'Black':['Small', 'Medium', 'Large'], 'Yellow/Fuschia':['Large', 'Extra Large']}

谢谢!


Python中的< 3.6 versions are词典和reinserting meaningless sorting是无序的。P></

as a fix,毋宁P></

  • python3.6(Switch to keep the caveats在心灵),或P></

  • OrderedDict使用安P></

  • realColor = {}option for the second,与collections.OrderedDict:replaceP></

    1
    2
    from collections import OrderedDict    
    realColor = OrderedDict()

    这是安安OrderedDictexample of how the Order of remembers安置:P></

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    dict1 = {}
    dict1['k'] = 1
    dict1['aSDFDF'] = 1234

    print(dict1) # {'aSDFDF': 1234, 'k': 1}

    from collections import OrderedDict
    dict2 = OrderedDict()
    dict2['k'] = 1
    dict2['aSDFDF'] = 1234

    print(dict2) # OrderedDict([('k', 1), ('aSDFDF', 1234)])

    好茶__repr__可能不同,但后者仍然在dictionary is the can be used accordingly布尔。P></