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


raymond --> red
rachel --> green
matthew --> blue

In [3]:
from itertools import izip

for name, color in izip(names, colors):
    print name, '-->', color


raymond --> red
rachel --> green
matthew --> blue

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]:
{'blue': 1, 'green': 2, 'red': 3}

In [6]:
d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1
d


Out[6]:
{'blue': 1, 'green': 2, 'red': 3}
Grouping with dictionaries

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]:
{5: ['roger', 'betty'],
 6: ['rachel', 'judith'],
 7: ['raymond', 'matthew', 'melissa', 'charlie']}

In [9]:
d = {}
for name in names:
    key = len(name)
    d.setdefault(key, []).append(name)
d


Out[9]:
{5: ['roger', 'betty'],
 6: ['rachel', 'judith'],
 7: ['raymond', 'matthew', 'melissa', 'charlie']}

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]:
(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']})