from collections import defaultdict Trie = lambda: defaultdict(Trie) trie = Trie() for row in ['abc', 'ab', 'abcd']: now = trie for ch in row: now = now[ch]