Skip to content

Instantly share code, notes, and snippets.

@sidharthshah
Last active May 13, 2017 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidharthshah/5610e43797fe49b50359208c09e2d6d0 to your computer and use it in GitHub Desktop.
Save sidharthshah/5610e43797fe49b50359208c09e2d6d0 to your computer and use it in GitHub Desktop.
Sample Python Code
# This is Readable
>>> nums = []
>>> for i in range(1000):
... nums.append(random.randint(1, 1000))
...
# This is not readable
num_1 = [random.randint(1, 1000) for i in range(1000)]
# Traditional way of doing things
counts = {}
for i in num:
if i not in counts:
counts[i] = 0
counts[i] += 1
# A little faster ways of doing things
counts = defaultdict(int)
for i in num:
counts[i] += 1
# Interating over dictionary
# One Way
for key, count in counts.items():
if count > 1:
print key, count
# Another Way
for current in names:
print current, "->", names[current]
# Code Sample to Count Articles by Source
import json
from collections import defaultdict
data = json.loads(open("data.json"))
counts_by_source = defaultdict(int)
for doc in data['response']['docs']:
counts_by_source[doc['source']] += 1
for store, count in counts_by_source.item():
print store, count
# Version with Reverse Sorting
import json
import operator
from collections import defaultdict
data = json.loads(open("data.json").read())
counts_by_source = defaultdict(int)
for current_article in data['response']['docs']:
counts_by_source[current_article['source']] += 1
for source, count in counts_by_source.items():
print source, count
print "\n\nSorted\n\n"
counts_by_source_sorted = sorted(
counts_by_source.items(),
key=operator.itemgetter(1),
reverse=True)
for source, count in counts_by_source_sorted:
print source, count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment