Home > Blockchain >  Python: Print stuff in dictionary line by line
Python: Print stuff in dictionary line by line

Time:04-11

I have an assignment where If I input a string for example

food food games hi food

it would print out like this:

food: 3
games: 1
hi: 1

the code I made right now is

def count_word(string1):
    counts = {}
    words = string1.split()

    for word in words:
        if word in  counts:
            counts[word]  = 1
        else:
            counts[word] = 1

    return counts

string1 = str(input())
print(count_word(string1))

If I input the same string as above it prints out:

{'food': 3, 'games': 1, 'hi': 1}

how do I make it so it prints out like this:

food: 3
games: 1
hi: 1

CodePudding user response:

Following should work:


d = {'food': 3, 'games': 1, 'hi': 1} # generated by counter function

for word, count in d.items():
    print(f'{word}: {count}')

if you want this sorted alphabetically replace d.items() with sorted(d.items()).

CodePudding user response:

dsic = {'food': 3, 'games': 1, 'hi': 1}

you could try somthing like this maybe:

import json 
print(json.dumps(dsic, sort_keys=False, indent=4))

or this one:

for i,x in dsic.items():
    print(str(i) ': '    str(x))

CodePudding user response:

You should do your research before posting on stackoverflow. For now, Hint is to use two loops. One for the list and one for printing the string.

  • Related