w3resource

Python: Create and display all combinations of letters, selecting each letter from a different key in a dictionary

Python dictionary: Exercise-21 with Solution

Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary.

Visual Presentation:

Python Dictionary: Create and display all combinations of letters, selecting each letter from a different key in a dictionary.

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 

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.



Follow us on Facebook and Twitter for latest update.