Python: Create and display all combinations of letters, selecting each letter from a different key in a dictionary
21. Create Combinations of Letters from Dictionary Keys
Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary.
Visual Presentation:

Sample Solution:
Python Code:
# Import the 'itertools' module, which provides tools for working with iterators and iterable objects.
import itertools
# Create a dictionary 'd' with keys '1' and '2', and associated lists of characters as values.
d = {'1': ['a', 'b'], '2': ['c', 'd']}
# Iterate through combinations of values from the dictionary 'd' using 'itertools.product'.
# The values are sorted based on their keys to ensure a specific order.
for combo in itertools.product(*[d[k] for k in sorted(d.keys())]):
# Print the combinations as strings by joining the characters in each combination.
print(''.join(combo))
Sample Output:
ac ad bc bd
For more Practice: Solve these Related Problems:
- Write a Python program to generate all combinations of letters by selecting one letter from each list in a dictionary.
- Write a Python program to use itertools.product to create all letter combinations from a dictionary of lists.
- Write a Python program to recursively combine letters from different keys in a dictionary and print each combination.
- Write a Python program to implement a function that outputs a list of strings formed by all possible combinations of values from a dictionary's keys.
Python Code Editor:
Previous: Write a Python program to print all unique values in a dictionary.
Next: Write a Python program to find the highest 3 values of corresponding keys in a dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.