Python: Remove duplicates from Dictionary
Python dictionary: Exercise-17 with Solution
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']}}
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.
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/dictionary/python-data-type-dictionary-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics