按字母顺序对字典排序,并按频率打印 [英] Sort a dictionary alphabetically, and print it by frequency

查看:81
本文介绍了按字母顺序对字典排序,并按频率打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Mac上运行python 2.7.2.

I am running python 2.7.2 on a mac.

我有一个简单的字典:

dictionary= {a,b,c,a,a,b,b,b,b,c,a,w,w,p,r}

我希望将其打印并具有如下输出:

I want it to be printed and have the output like this:

Dictionary in alphabetical order:
    a  4
    b  5
    c  2
    p  1
    r  1
    w  2

但是我得到的是这样的东西...

But what I'm getting is something like this...

a  1
a  1
a  1
a  1
b  1
.
.
.
w  1

这是我正在使用的代码.

This is the code I am using.

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

您能告诉我哪里出了错吗?(顺便说一句,我不是程序员,而是语言学家,所以请放轻松.)

Can you please tell me where is the mistake? (By the way, I'm not a programmer but a linguist, so please go easy on me.)

推荐答案

您使用的不是字典,而是

What you're using is not a dictionary, it's a set! :)

并且集合不允许重复.

您可能需要的不是字典,而是列表.

What you probably need is not dictionaries, but lists.

一些解释

字典有键,每个唯一键都有自己的值:

Dictionaries have keys, and each unique keys have their own values:

my_dict = {1:'a', 2:'b', 3:'c'} 

您可以使用以下键检索值:

You retrieve values by using the keys:

>>> my_dict [1]
'a'

另一方面,列表没有键.

On the other hand, a list doesn't have keys.

my_list = ['a','b','c']

然后使用它们的索引检索值:

And you retrieve the values using their index:

>>> my_list[1]
'b'

请记住,索引从零开始计数,而不是从1开始计数.

Keep in mind that indices starts counting from zero, not 1.

解决问题

现在,解决您的问题.首先,将字符存储为列表:

Now, for your problem. First, store the characters as a list:

l = ['a', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'a', 'w', 'w', 'p', 'r']

接下来,我们需要知道此列表中的哪些项目:

Next, we'll need to know what items are in this list:

items = []
for item in l:
    if item not in items:
        items.append(item)

这几乎等于 items = set(l)(唯一的区别是这是一个列表).但是,为了使事情更清楚,希望您理解代码的作用.

This is pretty much equal to items = set(l) (the only difference is that this is a list). But just to make things clear, hope you understand what the code does.

以下是项目的内容:

>>> items
['a', 'b', 'c', 'w', 'p', 'r']

完成后,我们将使用 lst.count() 方法来查看列表中char的出现次数,以及内置函数

With that done, we will use lst.count() method to see the number of a char's occurence in your list, and the built-in function sorted() to sort the items:

for item in sorted(items): #iterates through the sorted items.
    print item, l.count(item)

结果:

a 4
b 5
c 2
w 2
p 1
r 1

希望这会有所帮助!

这篇关于按字母顺序对字典排序,并按频率打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆