How to iterate over each pair of items in a dictionary
Question: I'm making a gravity simulator and I need to calculate the resultant force
acting upon each body.

In order to do this, I need to iterate through every pair of bodies in a
dictionary `(id: instance of Body class)` and get the gravitational force
between those two bodies. Then, I would add up all the forces and get the
resultants.

But, how do I iterate over each pair of items in a dictionary only once in
Python? If the celestial bodies were kept in a list, it would be simple:

    
    
    for i in range(len(bodies)):
        for j in range(len(bodies) - i - 1):
            k = j - i + 1
            b1 = bodies[i]
            b2 = bodies[k]
    


Answer: [`values()`](http://docs.python.org/library/stdtypes.html#dict.values) and
`itertools`'
[`combinations`](http://docs.python.org/library/itertools.html#itertools.combinations)
are ideal for this use case.

    
    
    from itertools import combinations
    for a, b in combinations(bodies.values(), 2):
        print a, b
    

