Issue
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.
Solution
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()}
Answered By - j1-lee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.