Skip to content

Instantly share code, notes, and snippets.

@iluxonchik
Last active August 26, 2016 07:06
Show Gist options
  • Save iluxonchik/348838b3547abf09587d5b4bcbb56f26 to your computer and use it in GitHub Desktop.
Save iluxonchik/348838b3547abf09587d5b4bcbb56f26 to your computer and use it in GitHub Desktop.
Alternative implementation of namescount.py using collections.defaultdict from the blog post "Why You Should Learn Python" https://iluxonchik.github.io/why-you-should-learn-python/
#!/usr/bin/env python3
import sys
from collections import defaultdict
def count_names():
names = defaultdict(int)
for name in sys.stdin.readlines():
name = name.strip()
names[name] += 1
for name, count in names.items():
sys.stdout.write("{0}\t{1}\n".format(name, count))
if __name__ == "__main__":
count_names()
@lazydroid
Copy link

lazydroid commented Aug 26, 2016

should have used "Counter" instead:

from collections import Counter
counts = Counter([i.strip() for i in sys.stdin.readlines()])

and that's it =)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment