<p>I have a list of tuples like this:</p>

<pre><code>[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
</code></pre>

<p>I want to iterate through this keying by the first item, so, for example, I could print something like this:</p>

<pre><code>a 1 2 3
b 1 2
c 1
</code></pre>

<p>How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...</p>

```
```
l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]

d = {}
for x, y in l:
    d.setdefault(x, []).append(y)
print d
```
```
produces:
```
```
{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
```
```