Search code examples
pythondictionarykeydefaultdict

Getting the values of many defaultdicts that contains a certain key


I have several defaultdict that looks like this:

en1 = {1:['handler', 'coach', 'manager'],2:['a','c']}
es2 = {1:['entrenador', 'míster', 'entrenadora'],2:['h','i'],4:['j','k','m']}
it3 = {1:['mister', 'allenatore' 'coach'],3:['p','q'],5:['r','q']}
...

And I need get the string from each defaultdict sharing the same index. Something like this:

for i in en1:
  for j in en1[i]:
    for k in es2[i]:
      for l in it3[i]:
        print j, k, l

but i have to do it for like 30+ defaultdict, so how can that be done without write that horrendous loop above?

Is there a way to get all the values of the defaultdict with the same keys and then output the values easily?

It should output combinations of tuples made up of values sharing the same key for all dicts, e.g.:

handler entrenador mister
handler entrenador allenatore
handler entrenador coach
handler mister mister
handler mister allenator
...

Solution

  • Start with using a list of dictionaries instead of 30 separate variables:

    dd = [{1: ['a', 'b'], 2: ['a', 'c'], 3: ['d', 'e']}, {1: ['f', 'g', 'l'], 2: ['h', 'i'], 4: ['j', 'k', 'm']}, ...]
    

    And use itertools.product() to generate all combinations between matching contained lists:

    from itertools import product
    
    for key in dd[0]:
        for combination in product(*(d[key] for d in dd)):
            print ' '.join(combination)
    

    Here the generator expression retrieves the same key from all dictionaries in one statement.

    Output for your sample input; note, there is no dd2[3] and no dd3[2], so for keys 2 and 3 no output is generated.

    >>> for key in dd[0]:
    ...     for combination in product(*(d[key] for d in dd)):
    ...         print ' '.join(combination)
    ... 
    handler entrenador mister
    handler entrenador allenatorecoach
    handler míster mister
    handler míster allenatorecoach
    handler entrenadora mister
    handler entrenadora allenatorecoach
    coach entrenador mister
    coach entrenador allenatorecoach
    coach míster mister
    coach míster allenatorecoach
    coach entrenadora mister
    coach entrenadora allenatorecoach
    manager entrenador mister
    manager entrenador allenatorecoach
    manager míster mister
    manager míster allenatorecoach
    manager entrenadora mister
    manager entrenadora allenatorecoach
    

    Looping over many keys then producing products from 30 different lists is going to take a while. You may have to rethink what you are trying to do and avoid doing too much work.