Thanks to Raymond Hettinger for his presentation Transforming Code into Beautiful, Idiomatic Python.
In [1]:
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']
In [2]:
for name, color in zip(names, colors):
print name, '-->', color
In [3]:
from itertools import izip
for name, color in izip(names, colors):
print name, '-->', color
Counting with dictionaries
In [4]:
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
In [5]:
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
d
Out[5]:
In [6]:
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1
d
Out[6]:
In [7]:
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
In [8]:
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
d
Out[8]:
In [9]:
d = {}
for name in names:
key = len(name)
d.setdefault(key, []).append(name)
d
Out[9]:
In [10]:
from collections import defaultdict
In [11]:
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)
d, dict(d)
Out[11]: