Is there an easy way to reorder a list of values in a dictionary alphabetically while keeping the order of the keys the same? I'm not looking to sort the dictionary by values just alphabetically order the lists of them. Thanks
-
If you changed the order of a dictionary using each keys value how would the order of the keys __not__ change? Your question makes no sense, maybe examples would help – Iain Shelvington May 04 '22 at 02:14
-
Dictionaries are inherently unordered. Meaning they can move what order the keys are in. So you can't really make a list of alphabetically ordered dictionaries because the dictionaries will each have their orders change. So there is no "first" key in a dictionary to use as how you are alphabetizing the list. – Rashid 'Lee' Ibrahim May 04 '22 at 02:15
-
2@Rashid this has been incorrect for a while now. Dictionary key in python are now [guaranteeing keeping inserting order](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6#:~:text=on%20this%20post.-,Are%20dictionaries%20ordered%20in%20Python%203.6%2B%3F,the%20order%20of%20items%20inserted.). – mozway May 04 '22 at 02:24
-
It's really unclear what you're asking for here. An example might help. – Mark Ransom May 04 '22 at 03:00
2 Answers
Assuming you want to sort the values independently of the keys (which can change the key: value association), you can create a new dictionary:
d = {'b': 1, 'c': 0, 'a': 2}
d2 = dict(zip(d, sorted(d.values())))
Output: {'b': 0, 'c': 1, 'a': 2}
Maybe I'm overthinking this and you just want:
sorted(d.values())
# [0, 1, 2]

- 194,879
- 13
- 39
- 75
Assuming you just didn't care about the old data ordering, you could just run this function:
def alphabetizeDictValues(dictionary):
for key in dictionary:
dictionary[key].sort()
The sort function of a list sorts the list in-place (making it lossy), so this would only work if you didn't care about the old ordering. This means that the memory requirement is lower, but also means you don't have a reference to how your list was previously sorted. Alternatively, if you wanted to save the old ordering, you could create this function
def alphabetizeDictValues(dictionary):
dupeDictionary = {}
for key in dictionary:
oldLst = list(dictionary[key])
dupeDictionary[key] = oldLst
dictionary[key].sort()
return dupeDictionary
This would return a copy of the input dictionary (with lists not sorted) while the dictionary you passed in would be the sorted version.

- 1
- 1