0

I have this line of code that organizes the words in list into dictionary by the first letter:

for a in list: dictionary[a[0]].append(a)

The problem is, this requires the dictionary keys to each individually have empty list values. I could do this by adding a few extra lines of code previously, but I want to know if there's a way to have the previous line of code deal with this.

Here's the pseudo-code:

  • If the key exists, insert a into dictionary[a[0]].
  • If it does not, do it after creating the key with an empty list.

Is there a way I can do this in a single line of code?

martineau
  • 119,623
  • 25
  • 170
  • 301
Douglas
  • 1,304
  • 10
  • 26

2 Answers2

7

You can use a defaultdict and not have to change your line of code at all:

from collections import defaultdict
dictionary = defaultdict(list)

for a in list: dictionary[a[0]].append(a)
MrAlexBailey
  • 5,219
  • 19
  • 30
  • This works quite well! Is it also high performance, or is it better to just use regular dictionaries over multiple lines of code? Thank you! – Douglas Jan 06 '17 at 15:20
  • @Douglas A quick test I ran shows this way to be faster than an equal method of using if / then to check for the keys in the dict first. – MrAlexBailey Jan 06 '17 at 16:51
  • That's very helpful, I'll use this a lot. Thank you for your help/time! – Douglas Jan 06 '17 at 20:04
4

You can do this with collections.defaultdict

>>> import collections
>>> dict_of_lists = collections.defaultdict(list)
>>> dict_of_lists['foo'].append('bar')
>>> print(dict_of_lists)
defaultdict(<class 'list'>, {'foo': ['bar']})
>>> 
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153