DEV Community

Cover image for Beginner Python tips Day - 03 defaultdict
Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

Beginner Python tips Day - 03 defaultdict

# 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 

Top comments (0)