0

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.

0

2 Answers 2

3

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()}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.