import collections sentence = "No, I shouldn't be glad, YOU should be glad." d = collections.defaultdict(list) words = sentence.split() for k, v in zip(words[:-1], words[1:]): d[k].append(v) print(d)
It creates
defaultdict(<type 'list'>, {'No,': ['I'], 'be': ['glad,', 'glad.'], 'glad,': ['YOU'], 'I': ["shouldn't"], 'should': ['be'], "shouldn't": ['be'], 'YOU': ['should']})
@NLS: I just wanted to add something. "d = collections.defaultdict (list)", like the dict object, does not preserve the word order, so if we need to preserve the order of the sentence, we may have to use a tuple.
Harry source share