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
CodePudding user response:
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.
CodePudding user response:
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]