【发布时间】:2013-10-29 06:00:25
【问题描述】:
我在 mac 上运行 python 2.7.2。
我有一本简单的字典:
dictionary= {a,b,c,a,a,b,b,b,b,c,a,w,w,p,r}
我希望它被打印出来并有这样的输出:
Dictionary in alphabetical order:
a 4
b 5
c 2
p 1
r 1
w 2
但我得到的是这样的......
a 1
a 1
a 1
a 1
b 1
.
.
.
w 1
这是我正在使用的代码。
new_dict = []
for word in dictionary.keys():
value = dictionary[word]
string_val = str(value)
new_dict.append(word + ": " + string_val)
sorted_dictionary = sorted(new_dict)
for entry in sorted_dictionary:
print entry
你能告诉我错误在哪里吗? (顺便说一句,我不是程序员而是语言学家,所以请放轻松。)
【问题讨论】:
-
dictionary的语法错误。请使用您在程序中使用的语法进行更正 -
这是一个
set,不是字典,第二个你将它声明为文字,它会删除所有重复项。 -
随便吧,还不如字典!
-
OrderedDict和Counter是选项。 -
@Pajamas 检查我的答案。
标签: python dictionary tabular alphabetical