Python: Remove duplicates from Dictionary
17. Remove Duplicates from the Dictionary
Write a Python program to remove duplicates from the dictionary.
Visual Presentation:
Sample Solution:
Python Code:
# Create a nested dictionary 'student_data' containing information about students with unique IDs.
student_data = {
'id1': {
'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id2': {
'name': ['David'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id3': {
'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id4': {
'name': ['Surya'],
'class': ['V'],
'subject_integration': ['english, math, science']
}
}
# Create an empty dictionary 'result' to store unique student records.
result = {}
# Iterate through the key-value pairs in the 'student_data' dictionary using a for loop.
for key, value in student_data.items():
# Check if the current 'value' (student record) is not already in the 'result' dictionary.
if value not in result.values():
# If the 'value' is not already in 'result', add it to 'result' with its corresponding 'key'.
result[key] = value
# Print the 'result' dictionary containing unique student records.
print(result)
Sample Output:
{'id2': {'subject_integration': ['english, math, science'], 'class': ['V'], 'name': ['David']}, 'id4': {'subje ct_integration': ['english, math, science'], 'class': ['V'], 'name': ['Surya']}, 'id1': {'subject_integration' : ['english, math, science'], 'class': ['V'], 'name': ['Sara']}}
For more Practice: Solve these Related Problems:
- Write a Python program to remove duplicate key-value pairs from a dictionary where values are lists by merging duplicates.
- Write a Python program to filter a dictionary so that each value appears only once, keeping the first occurrence.
- Write a Python program to implement a function that removes duplicate items from a dictionary and returns a new dictionary with unique values.
- Write a Python program to consolidate duplicate keys in a dictionary by summing their values.
Python Code Editor:
Previous: Write a Python program to get a dictionary from an object's fields.
Next: Write a Python program to check a dictionary is empty or not.
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