简体   繁体   中英

python : how to order lists of dictionary values alphabetically, keeping to order of the dictionary the same, not sorting the dict by value

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

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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM