How does the max_list
variable list comprehension work?
def mode(*args):
dict_vals = {i: args.count(i) for i in args}
max_list = [k for k, v in dict_vals.items() if v == max(dict_vals.values())]
return max_list
I know that the dict_vals
creates a dictionary that holds onto the values you enter (the key) and the number of occurrences for each value (the value of the key). I also know that max_list
creates a list of the keys (values) that occur the most based on the being the maximum value (occurrence).
I am just wanting to know how the comprehension used in max_list
works and maybe some other examples of turning dictionaries into lists with similar syntax for useful applications. Also, is there similar ways to do this with tuples?
dict_vals.items()
The items()
method yields each key-value pair in the dictionary.
k, v in dict_vals.items()
This iterates over each key-value pair in the dictionary yielded by items()
k, v in dict_vals.items() if v == max(dict_vals.values())
This filters that list of key-value pairs by selecting only those pairs where the value is equal to maximum in value stored in the dict_vals
(.values()
gives you all the values & max()
finds the largest among those).
Finally,
k for k,v in dict_vals.items() if v == max(dict_vals.values())
Selects only the key (k
) for those pairs. The []
makes it a list.