Python – How to iterate through each pair of items in a dictionary

How to iterate through each pair of items in a dictionary… here is a solution to the problem.

How to iterate through each pair of items in a dictionary

I’m working on a gravity simulator and I need to calculate the resultant force acting on each object.

To do this, I need to iterate through each pair of objects in the dictionary (an instance of the id:Body class) and get the gravitational pull between the two objects. Then, I would add up all the forces and get the result.

But how to iterate only once for every pair of items in the dictionary in Python? If you keep celestial objects in a list, it’s 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]

Solution

values() and itertools> combinations are well suited for this use case.

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

Related Problems and Solutions