-3

I'm having trouble sorting my dictionary alphabetically by its keys.

Here's my code:

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)

What I get:

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

What I wanna get:

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

Thanks!

cs95
  • 379,657
  • 97
  • 704
  • 746
John Does
  • 31
  • 1
  • 2
  • 5
    You can't sort a dict, because dicts don't have an order. Take a look at [`collections.OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict). – Aran-Fey Aug 18 '17 at 12:17
  • Python `dict`'s are unordered by default. You should either create a list of tuples from it and sort it, or consider [`OrderedDict`](https://docs.python.org/3/library/collections.html#ordereddict-objects). – Oleksii Filonenko Aug 18 '17 at 12:18

1 Answers1

2

Dictionaries in python versions < 3.6 are unordered, sorting and reinserting is meaningless.


As a fix, either

  1. Switch to python3.6 (keep in mind the caveats), or

  2. Use an OrderedDict

For the second option, replace realColor = {} with a collections.OrderedDict:

from collections import OrderedDict    
realColor = OrderedDict()

Here's an example of how an OrderedDict remembers the order of insertion:

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

The __repr__ might be different, but the latter is still a dictionary and can be used accordingly.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • thanks a lot! any idea on how to remove the 'OrderedDict(.....)' ? – John Does Aug 18 '17 at 12:21
  • @JohnDoes Like I said, the `__repr__` (as in, how it is printed out) is different, but it is used _exactly_ the same as a normal dictionary. – cs95 Aug 18 '17 at 12:21
  • 1
    `dict`s being ordered in Python 3.6 are an implementation detail, not an official language feature. So probably not a good idea to rely on it. [(source)](https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation) – glibdud Aug 18 '17 at 12:22