0

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.

QLimbo
  • 163
  • 7
  • 2
    If you want them all in one dict you should put them in one dict. You are creating a separate dict for each key:value pair. – Kenny Ostrom Oct 09 '22 at 16:52

3 Answers3

1

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.)

Later when you learn about list- and dict-comprehensions, you will find it easier and more readable to write:

def sort_dictionary(dic):
    return {k: sorted(v) for k, v in dic.items()}
j1-lee
  • 13,764
  • 3
  • 14
  • 26
1

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)
1

You can use dict.update() to update the value:

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

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

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

Or update while iterating it:

def sort_dictionary(dic: dict) -> dict:
    for i, j in dic.items(): 
        dic.update({i: sorted(j)})
    return dic

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

# {'b': ['a', 'd'], 'a': ['c', 'f']}
Arifa Chan
  • 947
  • 2
  • 6
  • 23