You can use collections.Counter for this. Example -
line = ['The', 'cat', 'chased', 'the', 'dog','the','dog'] from collections import Counter output = {} for i, item in enumerate(line): print(i, item, len(line)) if i != len(line) - 1: output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1})) print(output)
.setdefault() first checks to see if a key exists if it does not set it in the second argument, and then returns a value on that key.
In Counter, when you do .update() , if the key already exists, it increments the count by 1, so this seems like the correct structure used for your case.
In addition, Counter behaves just like a regular dictionary, so you can use them just like any dictionary.
Demo (note the modified input to show the scenario in which 'dog' followed 'the' twice) -
>>> line = ['The', 'cat', 'chased', 'the', 'dog','the','dog'] >>> from collections import Counter >>> output = {} >>> for i, item in enumerate(line): ... print(i, item, len(line)) ... if i != len(line) - 1: ... output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1})) ... 0 The 7 1 cat 7 2 chased 7 3 the 7 4 dog 7 5 the 7 6 dog 7 >>> print(output) {'dog': Counter({'the': 1}), 'cat': Counter({'chased': 1}), 'chased': Counter({'the': 1}), 'the': Counter({'dog': 2, 'cat': 1})}