python list comprehension for loop

Let’s make a ‘python list & dictionary comprehension for loop’ example. It selects equal or greater than average value, then returns max 50 elements from dictionary.


def pick_biggest_elements(my_dict):
values = [x for x in my_dict.values()]
values.sort()
average = sum(values) / float(len(values))
upper_side = [el for el in values if el >= average]
temp = [key for key, value in my_dict.items() if value in upper_side]
if len(temp) > 50:
temp = temp[-50:]
return [eval(a) for a in temp]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s