keys_dict doesn't contain anything, yet you are trying to access the key `row['type']` this will always be a key error, use `collections.defaultdict` or `keys_dict.setdefault(row['type'], {})`.