How can I simplify my code in an efficient way?
<p>so currently im stuck on a question of my assignment,
the assignment question is:
Define the print_most_frequent() function which is passed two parameters, a dictionary containing words and their corresponding frequencies (how many times they occurred in a string of text), e.g.,</p>

<pre><code>{"fish":9,  "parrot":8,  "frog":9,  "cat":9,  "stork":1,  "dog":4, "bat":9,  "rat":4}
</code></pre>

<p>and, an integer, the length of the keywords in the dictionary which are to be considered. </p>

<p>The function prints the keyword length, followed by " letter keywords: ", then prints a sorted list of all the dictionary keywords of the required length, which have the highest frequency, followed by the frequency.  For example, the following code:</p>

<pre><code>word_frequencies = {"fish":9,  "parrot":8,  "frog":9,  "cat":9,  "stork":1,  "dog":4, "bat":9,  "rat":4}

print_most_frequent(word_frequencies,3)   
print_most_frequent(word_frequencies,4)
print_most_frequent(word_frequencies,5)
print_most_frequent(word_frequencies,6)
print_most_frequent(word_frequencies, 7) 
</code></pre>

<p>prints the following:</p>

<pre><code>3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8
7 letter keywords: [] 0
</code></pre>

<p>I have coded to get the answer above however it is saying I'm wrong. Maybe it needs a simplifying but i'm struggling how to. Could someone help thank you.</p>

<pre><code>def print_most_frequent(words_dict, word_len):
    word_list = []
    freq_list = []
    for word,freq in words_dict.items():
        if len(word) == word_len:
            word_list += [word]
            freq_list += [freq]
    new_list1 = []
    new_list2 = []
    if word_list == [] and freq_list == []:
        new_list1 += []
        new_list2 += [0]
        return print(new_list1, max(new_list2))
    else:
        maximum_value = max(freq_list)
        for i in range(len(freq_list)):
            if freq_list[i] == maximum_value:
                new_list1 += [word_list[i]]
                new_list2 += [freq_list[i]]
                new_list1.sort()
        return print(new_list1, max(new_list2))
</code></pre>

<p>You can use:</p>

<pre><code>def print_most_frequent(words_dict, word_len):
    max_freq = 0
    words = list()
    for word, frequency in words_dict.items():
        if len(word) == word_len:
            if frequency &gt; max_freq:
                max_freq = frequency
                words = [word]
            elif frequency == max_freq:
                words.append(word)
    print("{} letter keywords:".format(word_len), sorted(words), max_freq)
</code></pre>

<p>It just iterates over the words dictionary, considering only the words whose length is the wanted one and builds the list of the most frequent words, resetting it as soon as a greater frequency is found.</p>

python list dictionary