Tessa Ickx
Tessa Ickx

Reputation: 33

How to iterate over a dictionary in a specific way?

I'm trying to iterate over a dictionary in a specific way. Let's say my dictionary is like this:

d={'MERRY': [12996, 13225, 18225, 20449, 24336, 27556, 27889, 34225, 46225,
             52441, 61009, 62001, 63001, 64009, 70225, 73441, 81225],
   'XMAS': [1024, 1089, 1296, 1369, 1764, 1849, 1936, 2304, 2401, 2601, 2704,
            2809, 2916, 3025, 3249, 3481,3721, 4096, 4356, 4761, 5041, 5184,
            5329, 5476, 6084, 6241, 6724, 7056, 7396, 7569, 7921, 8649, 9025,
            9216, 9604, 9801],
   'TO': [16, 25, 36, 49, 64, 81],
   'ALL': [100, 144, 400, 900]}

First, I want to check the combinations:

12996 1024 16 100,
12996 1024 16 144,
12996 1024 16 400,
12996 1024 16 900,

After that: 12966 1024 25 100, etc.

I need to check all the possible combinations. Another solution is also fine by me.

I've tried doing it manually with a lot of for-loops, and that works.

The code worked for this example, but I need to expand it to a dictionary with up to 10 keys. I have no idea how to fix this.

This code shows an example for a dictionary with 4 keys:

for item in d['MERRY']:
    for item2 in d['XMAS']:
        for item3 in d['TO']:
            for item4 in d['ALL']:
                #make something out of items1,2,3 and 4
                if something == somethingelse:
                    #print(something)

Upvotes: 2

Views: 88

Answers (1)

Ilya
Ilya

Reputation: 541

Try this (compliments to @Prune):

from itertools import product
[p for p in product(*d.values())]

product() gives you an iterable. If you don't want the iterable blown up into a list right away, skip the list comprehension.

Upvotes: 3

Related Questions