DEV Community

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

Posted on

7 2

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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay