Take the 2-minute tour ×

I am trying to write a python program that takes a file with 14 lines each with three different values--


-- for example. I am just wondering if someone could help me split the example into the three seperate sections and then see how many times s1 or s2 was used and by which--- either s01, s02, or s03? if that makes any sense...

share|improve this question
You should post what you have attempted and ask specific questions. –  Caribou Nov 15 '12 at 0:00
add comment

1 Answer

How's this?

>>> from collections import defaultdict
>>> results = defaultdict(list)
>>> with open("data.txt") as f:
...     for line in f:
...         data = line.strip().split(":")
...         results[data[2]].append(data[0])
>>> results
defaultdict(<type 'list'>, {'s2': ['s02', 's01'], 's1': ['s01', 's03']})
>>> summary = dict([(k, len(v)) for k, v in results.items()])
>>> summary
{'s2': 2, 's1': 2}

In Python 2.7 and above, you can replace



summary = {k: len(v) for k, v in results.items()}
share|improve this answer
You can also use a collection.Counter object. –  Bitwise Nov 15 '12 at 2:42
add comment

Your Answer


