Home > other >  Double loop with Python dictionary avoiding repetitions
Double loop with Python dictionary avoiding repetitions

Time:07-05

Consider the following code snippet:

foo = {'a': 0, 'b': 1, 'c': 2}

for k1 in foo:
    for k2 in foo:
        print(foo[k1], foo[k2])

The output will be

0 0
0 1
0 2
1 0
1 1 
1 2
2 0
2 1 
2 2

I do not care for the order of the key couples, so I would like a code that outputs

0 0
0 1
0 2
1 1 
1 2
2 2

I tried with

foo = {'a': 0, 'b': 1, 'c': 2}

foo_2 = foo.copy()

for k1 in foo_2:
    for k2 in foo_2:
        print(foo[k1], foo[k2])
    foo_2.pop(k1)

but I clearly got

RuntimeError: dictionary changed size during iteration

Other solutions?

CodePudding user response:

>>> foo = {'a': 0, 'b': 1, 'c': 2}
>>> keys = list(foo.keys())
>>> for i, v in enumerate(keys):
...     for j, v2 in enumerate(keys[i:]):
...             print(foo[v], foo[v2])
... 
0 0
0 1
0 2
1 1
1 2
2 2

CodePudding user response:

foo = {'a': 0, 'b': 1, 'c': 2}

foo_2 = foo.copy()

for k1 in foo:
    for k2 in foo_2:
        print(foo[k1], foo[k2])
    foo_2.pop(k1)

CodePudding user response:

A basic approach.

foo = {'a': 0, 'b': 1, 'c': 2}

for v1 in foo.values():
    for v2 in foo.values():
        if v1 <= v2:
            print(v1, v2)

It could be done with itertools.combinations_with_replacement as well:

from itertools import combinations_with_replacement

foo = {'a': 0, 'b': 1, 'c': 2}

print(*[f'{foo[k1]} {foo[k2]}' for k1, k2 in combinations_with_replacement(foo.keys(), r=2)], sep='\n')
  • Related