Python:逐行打印字典中的内容



我有一个赋值,如果我输入一个字符串,例如

food food games hi food

它会像这样打印出来:

food: 3
games: 1
hi: 1

我现在做的代码是

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))

如果我输入与上面相同的字符串,它会打印出来:

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

我该怎么做才能把它打印成这样:

food: 3
games: 1
hi: 1

以下内容应该有效:


d = {'food': 3, 'games': 1, 'hi': 1} # generated by counter function
for word, count in d.items():
print(f'{word}: {count}')

如果要按字母顺序排序,请将d.items()替换为sorted(d.items())

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

你可以试试这样的东西:

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

或者这个:

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

在stackoverflow上发帖之前,你应该先做一下调查。目前,提示是使用两个循环。一个用于列表,一个用于打印字符串。

最新更新