Home > Software design >  How do I remove the curly bracket in my output of dictionary and replace with output i prefer?
How do I remove the curly bracket in my output of dictionary and replace with output i prefer?

Time:10-19

My output comes out in a curly bracket and dictionary style in a line but I would like it to format it differently. Ex: if input is "hello i am"

output:

am : 1
hello : 1 
i : 1

Here is my code:

def word_count(sent):
    
    i = dict()
    j = sent.split()
    j.sort()
    
    for word in j:
        if word in i:
            i[word]  = 1
        else:
            i[word] = 1

    return i
    
sent = input("Please provide the article: \n" ).lower()

x = word_count(sent)

print("Output: \n", x , '\n' )



print("X")

CodePudding user response:

Use collections.Counter, this is a subclass of dictionary:

from collections import Counter

sent = input("Please provide the article: \n" ).lower()

counts = Counter(sorted(sent.split()))

To output as string:

print('\n'.join(f'{k}: {v}' for k,v in counts.items()))

output:

am: 1
hello: 1
i: 1

CodePudding user response:

do:

def word_count(sent):
    
    i = dict()
    j = sent.split()
    j.sort()
    
    for word in j:
        if word in i:
            i[word]  = 1
        else:
            i[word] = 1
    for k in i:
        return f"{k}:{i[k]}"
  • Related