简体   繁体   中英

How to sort values of a dictionary?

I want to sort only VALUES of a dictionary but not KEYS . I have reversed the dictionary, so that's not an issue. I just want values to be sorted. Following is the code I've tried:

def reverse_dictionary(olddict):
newdict = {}
for key, value in olddict.items():
    for string in value:
        newdict.setdefault(string.lower(), []).append(key.lower())

for key, value in newdict.items():
    newdict[key] = sorted(value)
    return newdict

olddict=({'astute': ['Smart', 'clever', 'talented'],
          'Accurate': ['exact', 'precise'],  
          'exact': ['precise'], 
          'talented': ['smart', 'keen', 'Bright'], 
          'smart': ['clever', 'bright', 'talented']})
result=reverse_dictionary(olddict)
print(result)

The output I got is:

{'keen': ['talented'], 'precise': ['exact', 'accurate'], 
 'exact': ['accurate'], 'bright': ['talented', 'smart'], 
 'clever': ['smart', 'astute'], 'talented': ['smart', 'astute'], 
 'smart': ['talented', 'astute']}

The VALUES are not sorted in the output. Please help.

You are returning the dictionary at the first loop iteration:

for key, value in newdict.items():
    newdict[key] = sorted(value)
    return newdict

Instead, you could just return new dictionary using dictionary comprehension:

return {k: sorted(v) for k, v in newdict.items()}

You are returning out of your second for loop to early

def reverse_dictionary(olddict):
    newdict = {}
    for key, value in olddict.items():
        for string in value:
            newdict.setdefault(string.lower(), []).append(key.lower())

    for key, value in newdict.items():
        newdict[key] = sorted(value)
    return newdict

olddict=({'astute': ['Smart', 'clever', 'talented'],
          'Accurate': ['exact', 'precise'],
          'exact': ['precise'],
          'talented': ['smart', 'keen', 'Bright'],
          'smart': ['clever', 'bright', 'talented']})
result=reverse_dictionary(olddict)

print(result)

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