w3resource

Python: Create a dictionary from two lists without losing duplicate values

Python dictionary: Exercise-36 with Solution

Write a Python program to create a dictionary from two lists without losing duplicate values.

Visual Presentation:

Python Dictionary: Create a dictionary from two lists without losing duplicate values.

Sample Solution:

Python Code:

# Import the 'defaultdict' class from the 'collections' module.
from collections import defaultdict

# Create a list 'class_list' with class names and a list 'id_list' with corresponding IDs.
class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII']
id_list = [1, 2, 2, 3]

# Create a defaultdict 'temp' with set as the default factory function.
temp = defaultdict(set)

# Iterate through paired elements of 'class_list' and 'id_list' using the 'zip' function.
for c, i in zip(class_list, id_list):
    # Add the 'i' value to the set associated with the 'c' key in the 'temp' defaultdict.
    temp[c].add(i)

# Print the 'temp' defaultdict, which groups IDs by class name.
print(temp) 

Sample Output:

defaultdict(<class 'set'>, {'Class-V': {1}, 'Class-VI': {2}, 'Class-VII': {2}, 'Class-VIII': {3}})

Python Code Editor:

Previous: Write a Python program to sort Counter by value.
Next: Write a Python program to replace dictionary values with their sum.

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.