Python: Print a dictionary in table format
Write a Python program to print a dictionary in table format.
Sample Solution:
Python Code:
# Create a dictionary 'my_dict' with keys as 'C1', 'C2', and 'C3', and corresponding lists of values.
my_dict = {'C1': [1, 2, 3], 'C2': [5, 6, 7], 'C3': [9, 10, 11]}
# Use a list comprehension to create a list of tuples where each tuple contains a key and its corresponding list of values.
# Sort the items (key-value pairs) in the 'my_dict' dictionary based on their keys.
# The 'zip' function is used to transpose the rows and columns.
for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
# Print each row of transposed data as space-separated values.
print(*row)
Sample Output:
C1 C2 C3 1 5 9 2 6 10 3 7 11
Python Code Editor:
Previous: Write a Python program to create a dictionary from a string.
Next: Write a Python program to count the values associated with key in a dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics