Home > Enterprise >  Sort dictionary values alphabetically, where the order of the keys is not important
Sort dictionary values alphabetically, where the order of the keys is not important

Time:10-10

I have just started learning dictionaries and I have a problem with one task that requires me to sort dictionary values alphabetically.

def sort_dictionary(dic: dict) -> dict:
    for i, j in dic.items():
        sorted_dict = {i: sorted(j)}
        print(sorted_dict)

So, for example print(sort_dictionary({"b":["d", "a"], "a":["c", "f"]})) should give me {"b":["a", "d"], "a":["c", "f"]}. My code gives

{'b': ['a', 'd']}
{'a': ['c', 'f']}

How can this be fixed? Also, if possible, I will ask you not to use lambda, since I have not yet learned it.

CodePudding user response:

Try:

def sort_dictionary(dic):
    sorted_dict = {}
    for i, j in dic.items():
        sorted_dict[i] = sorted(j)
    return sorted_dict

print(sort_dictionary({"b":["d", "a"], "a":["c", "f"]}))
# {'b': ['a', 'd'], 'a': ['c', 'f']}

In your current code, you are making sorted_dict with only one key, print it, and then throw it away at each iteration. You need to accumulate the "key: sorted list" pair at each iteration, and then return the complete dictionary at the end, after you finish the for loop.

Also, you need to return the dictionary, not print the dictionary in the function. The caller print(sort_dictionary(...)) would obtain the output from the function, and then print it. (When you run your own code, you will see the code prints None. It is because you didn't write return in your code; in this case the function automatically returns None.)

CodePudding user response:

You can do in place sorting in the same dictionary:

def sort_dictionary(dic: dict) -> dict:
    for i, j in dic.items():
        j.sort()
    print(dic)
  • Related