[].append()
returns None
. You'd want to append to the return value of dict.setdefault()
instead. You also don't need to do a key containment test when using dict.setdefault()
; setdefault()
already makes that test for you.
Next, don't call object.__len__()
. Use len(object)
instead. I'd also use {}
instead of dict()
; the latter has to look up a name and make a function call, the {}
literal is compiled to a single bytecode to create a dictionary.
This works:
for i in range(len(text) - 1):
key = text[i:i + 1]
next_word = text[i + 1:i + 2]
chain.setdefault(key, []).append(next_word)
You could also use zip()
to pair up the letters:
for key, next_word in zip(text, text[1:]):
chain.setdefault(key, []).append(next_word)
Demo:
>>> text = "ABBBAACCCCAABBCCCCAABCBCBCABCCCA"
>>> chain = {}
>>> for key, next_word in zip(text, text[1:]):
... chain.setdefault(key, []).append(next_word)
...
>>> chain
{'A': ['B', 'A', 'C', 'A', 'B', 'A', 'B', 'B'], 'B': ['B', 'B', 'A', 'B', 'C', 'C', 'C', 'C', 'C'], 'C': ['C', 'C', 'C', 'A', 'C', 'C', 'C', 'A', 'B', 'B', 'A', 'C', 'C', 'A']}
>>> from pprint import pprint
>>> pprint(chain)
{'A': ['B', 'A', 'C', 'A', 'B', 'A', 'B', 'B'],
'B': ['B', 'B', 'A', 'B', 'C', 'C', 'C', 'C', 'C'],
'C': ['C', 'C', 'C', 'A', 'C', 'C', 'C', 'A', 'B', 'B', 'A', 'C', 'C', 'A']}