python - Sort dictionary by key alphabetically -
this question has answer here:
- how can sort dictionary key? 19 answers
i'm having trouble sorting dictionary
alphabetically keys
.
here's 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 = {} key in sorted(colorsizes.keys()): realcolor[key] = colorsizes.get(key) print(realcolor)
what get:
{'yellow/fuschia':['large', 'extra large'], 'black':['small', 'medium', 'large']}
what wanna get:
{'black':['small', 'medium', 'large'], 'yellow/fuschia':['large', 'extra large']}
thanks!
dictionaries in python versions < 3.6 unordered, sorting , reinserting meaningless.
as fix, either
switch python3.6 (keep in mind caveats), or
use
ordereddict
for second option, replace realcolor = {}
collections.ordereddict
:
from collections import ordereddict realcolor = ordereddict()
here's example of how ordereddict
remembers order of insertion:
dict1 = {} dict1['k'] = 1 dict1['asdfdf'] = 1234 print(dict1) # {'asdfdf': 1234, 'k': 1} collections import ordereddict dict2 = ordereddict() dict2['k'] = 1 dict2['asdfdf'] = 1234 print(dict2) # ordereddict([('k', 1), ('asdfdf', 1234)])
the __repr__
might different, latter still dictionary , can used accordingly.
Comments
Post a Comment