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