Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 976
John Carter Avatar asked Dec 07 '22 16:12

John Carter


2 Answers

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)
like image 120
David Z Avatar answered Dec 09 '22 16:12

David Z


Use dict's setdefault like this:

phone_book.setdefault('name', []).append(number)
like image 38
Piotr Findeisen Avatar answered Dec 09 '22 14:12

Piotr Findeisen