Python Forum
Functions returns content of dictionary as sorted list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Functions returns content of dictionary as sorted list (/thread-22663.html)



Functions returns content of dictionary as sorted list - kyletremblay15 - Nov-21-2019

I am trying to create a function in python 3.6 that returns a dictionary with count being the key and list being the value to gather all items with the same count.

This is what I have for code so far:
def sorted_dict_content(key_val):
    return [{k: key_val[k]}
    for k in sorted(key_val.keys(), reverse=True)]
While this code is functional, I am wondering if there is a way I can get the same output by creating a blank list, appending the key-value pairs to it, and returning this list.

Thanks for helping!


RE: Functions returns content of dictionary as sorted list - ichabod801 - Nov-21-2019

Any list comprehension of the form data = [expression(x) for x in sequence] can be written as a for loop:

data = []
for x in sequence:
   data.append(expression(x))