w3resource

Python: Split a given dictionary of lists into list of dictionaries using map function

Python map: Exercise-15 with Solution

Write a Python program to split a given dictionary of lists into list of dictionaries using the map function.

Sample Solution:

Python Code:

# Define a function named 'list_of_dicts' that takes a dictionary of lists as input
def list_of_dicts(marks):
    # Use a list comprehension to create a list of tuples, where each tuple represents a key-value pair from the input dictionary
    # Use the 'zip' function to transpose the list of tuples, creating tuples with values from the same position in each tuple
    # Use another list comprehension to convert each tuple into a dictionary
    # Use the 'map' function to apply the 'dict' constructor to each tuple, resulting in a map object of dictionaries
    # Convert the map object to a list and return the result
    result = map(dict, zip(*[[(key, val) for val in value] for key, value in marks.items()]))
    return list(result)

# Define a dictionary named 'marks' with keys representing subjects and values representing lists of marks
marks = {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}

# Print the original dictionary of lists
print("Original dictionary of lists:")
print(marks)

# Print a newline for better readability
print("\n")

# Print a message indicating the operation to be performed
print("Split said dictionary of lists into list of dictionaries:")

# Print the result of calling the 'list_of_dicts' function with the 'marks' dictionary
print(list_of_dicts(marks))

Sample Output:

Original dictionary of lists:
{'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]}

Split said dictionary of lists into list of dictionaries:
[{'Science': 88, 'Language': 77}, {'Science': 89, 'Language': 78}, {'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to interleave two given list into another list randomly using map() function.
Next: Write a Python program to convert a given list of strings into list of lists using map function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/map/python-map-exercise-15.php