Is there a nice idiom for adding a new list or adding to the list (if any) in the dictionary?

This is the second time I implemented something like this, and I suspect there should 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 understand that the code may be shorter with conditional assignments, but I suspect that probably the best way to do this. I'm not interested in making the code shorter.

+4
source share
2 answers

Use dict setdefault as follows:

 phone_book.setdefault('name', []).append(number) 
+7
source

Yes, you can use defaultdict . With this dict subclass, when accessing an element in the dictionary, if the value does not already exist, it automatically creates one of them using the constructor function you specify.

 from collections import defaultdict phone_book = defaultdict(list) def add_number(name, number): phone_book[name].append(number) 
+8
source

Source: https://habr.com/ru/post/1396753/


All Articles