This is the second time I've implemented something like this and I suspect there has to be a better (read: more pythonic) way to do this:
phone_book = {}
def add_number(name,number):
if name in phone_book:
phone_book['name'].append(number)
else:
phone_book['name'] = [number]
I realize the code can likely be made more concise with conditional assignments, but I suspect there's likely a better way to go about this. I'm not interested in only making the code shorter.
Yep, you can use defaultdict
. With this dict
subclass, when you access an element in the dictionary, if a value doesn't already exist, it automatically creates one using a constructor function you specify.
from collections import defaultdict
phone_book = defaultdict(list)
def add_number(name, number):
phone_book[name].append(number)
Use dict
's setdefault
like this:
phone_book.setdefault('name', []).append(number)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With