# Python Day-03 defaultdict
from collections import defaultdict
# You can specify the type of values the dictionary will contain
dict_of_list = defaultdict(list)
dict_of_list['languages'] = ['Python', 'JavaScript', 'Dart']
print(dict_of_list['languages'])
# Prints ['Python', 'JavaScript', 'Dart']
# when the key cannot be found empty list is returned
print(dict_of_list['frameworks'])
# Prints [] i.e empty list
dict_of_numbers = defaultdict(int)
dict_of_numbers['students'] = 10
print(dict_of_numbers['students'])
# Prints 10
print(dict_of_numbers['teachers'])
# Prints 0
# If the key isn't found return the predefined value
safe_dict = defaultdict(lambda : None)
safe_dict['hello'] = 'world'
print(safe_dict['hello'])
# Prints 'world'
print(safe_dict['world'])
# Prints None
![Cover image for Beginner Python tips Day - 03 defaultdict](https://media.dev.to/cdn-cgi/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fjq8i8mng8wn7kaxmmv5h.png)
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)