python 字典之一key->多值

来源:互联网 发布:mldonkey mac 编辑:程序博客网 时间:2024/06/08 03:35

python字典,键值对,但是有时候我们需要一键对应多个值,那么怎么办呢?

例如:test.txt文档中的内容如下:

1 key1
2 key2
3 key1
7 key3
8 key2
10 key1
14 key2
19 key4
20 key1
30 key3

现在要统计,每个key包含哪些序号,这就是一个典型的一键对多值。那么使用dict.setdefault可以轻松解决。

d={}

def statistic(txtpath):

     f=open(txtpath,'r')

    for line in f.readlines():

          num=line.split()[0]

          key=line.split()[1]

         d.setdefault(key,[]) .append(num)

     print d

1 0
原创粉丝点击