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