Search code examples
pythonlistdictionaryfrequencyitems

Dictionary won't be displayed as requested


I need to solve an exercise (for beginners!) and get as result the frequencies of all occurring characters in a given text. My problem is I am stuck with the function I have tried to write because instead of a dictionary I get a list as result. I am aware that the problem is probably to be found in the use of "[]" but I haven't found any better solution to get at least one result.

Here is what I am struggling with:

def character_frequency(text):
"""
Returns the frequences of all occuring characters in the given text
:param text: A text
:return: Dict in the form {"<character>": frequency, "<character>": frequency, ...}
"""

frequency = {}  # empty dict

    for line in text:
    for character in line.lower():
        if character in frequency:
            frequency[character] += 1
        else:
            frequency[character] = 1
            print(f"character{str(frequency)}")

return frequency

print()
print("excerise")
frequency = character_frequency(growing_plants)
for c, n in frequency.items():
    print(f"Character: {c}: {n}")

How should I change my function in order to get the correct dictionary result?


Solution

  • Firstly, I noticed your indentation is wrong.

    def character_frequency(text):
    """
    Returns the frequences of all occuring characters in the given text
    :param text: A text
    :return: Dict in the form {"<character>": frequency, "<character>": frequency, ...}
    """
    # Finding most occuring character
    
    # Set frequency as empty dictionary
    frequency_dict = {}
    
    for character in string:
        if character in frequency_dict:
            frequency_dict[character] += 1
        else:
            frequency_dict[character] = 1
    
    most_occurring = max(frequency_dict, key=frequency_dict.get)
    
    # Displaying result
    print("\nMost occuring character is: ", most_occuring)
    print("It is repeated %d times" %(frequency_dict[most_occurring]))