0

I try to use get method of dictionaries to avoid an if-else structure, but the method returns a None object, whereas I want a list. My code :

dic = {}
words = ['foo', 'bar']
for word in words :
    long = len(word)
    dic[long] = dic.get(long, []).append(word)

I want to have (at the end of the loop) :

{3:['foo', 'bar']}

But I have :

AttributeError: 'NoneType' object has no attribute 'append'

Which means that get returned a None object (default value)... where I though it should return a void list if the key doesn't exists, a list filled withs some strings if the key exists. Any ideas ?

  • You'll probably have an easier time if you just use [`collections.defaultdict`](https://docs.python.org/2.7/library/collections.html#collections.defaultdict). – BrenBarn Oct 20 '15 at 17:52

1 Answers1

-1
dic = {}
words = ['foo', 'bar']
for word in words :
    long = len(word)
    if (dic.has_key(long)):
        dic[long].append(word)
    else:
        dic[long] = [word]
o-90
  • 17,045
  • 10
  • 39
  • 63
pausag
  • 136
  • 8